forked from byJoey/yx-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudflare_speedtest.py
More file actions
4478 lines (3890 loc) · 176 KB
/
cloudflare_speedtest.py
File metadata and controls
4478 lines (3890 loc) · 176 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Cloudflare SpeedTest 跨平台自动化脚本
支持 Windows、Linux、macOS (Darwin)
支持完整的 Cloudflare 数据中心机场码映射
"""
import os
import sys
import platform
import subprocess
import requests
import json
import csv
import argparse
from pathlib import Path
from datetime import datetime
# 使用curl的备用HTTP请求函数(解决SSL模块不可用的问题)
def curl_request(url, method='GET', data=None, headers=None, timeout=30):
"""
使用curl命令进行HTTP请求(当requests的SSL模块不可用时使用)
Args:
url: 请求的URL
method: HTTP方法(GET, POST, DELETE等)
data: 请求数据(将被转换为JSON)
headers: 请求头字典
timeout: 超时时间(秒)
Returns:
dict: 包含status_code、json、text等属性的响应对象模拟
"""
cmd = ['curl', '-s', '-w', '\\n%{http_code}', '-X', method, '--connect-timeout', str(timeout)]
# 添加请求头
if headers:
for key, value in headers.items():
cmd.extend(['-H', f'{key}: {value}'])
# 添加请求数据
if data:
json_data = json.dumps(data)
cmd.extend(['-d', json_data])
# 添加URL
cmd.append(url)
try:
# 执行curl命令,指定编码为utf-8
result = subprocess.run(cmd, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout)
output = result.stdout
# 分离响应体和状态码
lines = output.strip().split('\n')
if len(lines) >= 1:
status_code = int(lines[-1])
response_text = '\n'.join(lines[:-1])
else:
status_code = 0
response_text = output
# 创建响应对象模拟
class CurlResponse:
def __init__(self, status_code, text):
self.status_code = status_code
self.text = text
self._json = None
def json(self):
if self._json is None:
self._json = json.loads(self.text) if self.text else {}
return self._json
return CurlResponse(status_code, response_text)
except subprocess.TimeoutExpired:
raise Exception("请求超时,请检查网络连接")
except subprocess.CalledProcessError as e:
raise Exception(f"curl命令执行失败: {e}")
except FileNotFoundError:
raise Exception("curl命令未找到,请确保系统已安装curl")
except Exception as e:
raise Exception(f"curl请求失败: {e}")
# Cloudflare 数据中心完整机场码映射
# 数据来源:Cloudflare 官方数据中心列表
AIRPORT_CODES = {
# 亚太地区 - 中国及周边
"HKG": {"name": "香港", "region": "亚太", "country": "中国香港"},
"TPE": {"name": "台北", "region": "亚太", "country": "中国台湾"},
# 亚太地区 - 日本
"NRT": {"name": "东京成田", "region": "亚太", "country": "日本"},
"KIX": {"name": "大阪", "region": "亚太", "country": "日本"},
"ITM": {"name": "大阪伊丹", "region": "亚太", "country": "日本"},
"FUK": {"name": "福冈", "region": "亚太", "country": "日本"},
# 亚太地区 - 韩国
"ICN": {"name": "首尔仁川", "region": "亚太", "country": "韩国"},
# 亚太地区 - 东南亚
"SIN": {"name": "新加坡", "region": "亚太", "country": "新加坡"},
"BKK": {"name": "曼谷", "region": "亚太", "country": "泰国"},
"HAN": {"name": "河内", "region": "亚太", "country": "越南"},
"SGN": {"name": "胡志明市", "region": "亚太", "country": "越南"},
"MNL": {"name": "马尼拉", "region": "亚太", "country": "菲律宾"},
"CGK": {"name": "雅加达", "region": "亚太", "country": "印度尼西亚"},
"KUL": {"name": "吉隆坡", "region": "亚太", "country": "马来西亚"},
"RGN": {"name": "仰光", "region": "亚太", "country": "缅甸"},
"PNH": {"name": "金边", "region": "亚太", "country": "柬埔寨"},
# 亚太地区 - 南亚
"BOM": {"name": "孟买", "region": "亚太", "country": "印度"},
"DEL": {"name": "新德里", "region": "亚太", "country": "印度"},
"MAA": {"name": "金奈", "region": "亚太", "country": "印度"},
"BLR": {"name": "班加罗尔", "region": "亚太", "country": "印度"},
"HYD": {"name": "海得拉巴", "region": "亚太", "country": "印度"},
"CCU": {"name": "加尔各答", "region": "亚太", "country": "印度"},
# 亚太地区 - 澳洲
"SYD": {"name": "悉尼", "region": "亚太", "country": "澳大利亚"},
"MEL": {"name": "墨尔本", "region": "亚太", "country": "澳大利亚"},
"BNE": {"name": "布里斯班", "region": "亚太", "country": "澳大利亚"},
"PER": {"name": "珀斯", "region": "亚太", "country": "澳大利亚"},
"AKL": {"name": "奥克兰", "region": "亚太", "country": "新西兰"},
# 北美地区 - 美国西海岸
"LAX": {"name": "洛杉矶", "region": "北美", "country": "美国"},
"SJC": {"name": "圣何塞", "region": "北美", "country": "美国"},
"SEA": {"name": "西雅图", "region": "北美", "country": "美国"},
"SFO": {"name": "旧金山", "region": "北美", "country": "美国"},
"PDX": {"name": "波特兰", "region": "北美", "country": "美国"},
"SAN": {"name": "圣地亚哥", "region": "北美", "country": "美国"},
"PHX": {"name": "凤凰城", "region": "北美", "country": "美国"},
"LAS": {"name": "拉斯维加斯", "region": "北美", "country": "美国"},
# 北美地区 - 美国东海岸
"EWR": {"name": "纽瓦克", "region": "北美", "country": "美国"},
"IAD": {"name": "华盛顿", "region": "北美", "country": "美国"},
"BOS": {"name": "波士顿", "region": "北美", "country": "美国"},
"PHL": {"name": "费城", "region": "北美", "country": "美国"},
"ATL": {"name": "亚特兰大", "region": "北美", "country": "美国"},
"MIA": {"name": "迈阿密", "region": "北美", "country": "美国"},
"MCO": {"name": "奥兰多", "region": "北美", "country": "美国"},
# 北美地区 - 美国中部
"ORD": {"name": "芝加哥", "region": "北美", "country": "美国"},
"DFW": {"name": "达拉斯", "region": "北美", "country": "美国"},
"IAH": {"name": "休斯顿", "region": "北美", "country": "美国"},
"DEN": {"name": "丹佛", "region": "北美", "country": "美国"},
"MSP": {"name": "明尼阿波利斯", "region": "北美", "country": "美国"},
"DTW": {"name": "底特律", "region": "北美", "country": "美国"},
"STL": {"name": "圣路易斯", "region": "北美", "country": "美国"},
"MCI": {"name": "堪萨斯城", "region": "北美", "country": "美国"},
# 北美地区 - 加拿大
"YYZ": {"name": "多伦多", "region": "北美", "country": "加拿大"},
"YVR": {"name": "温哥华", "region": "北美", "country": "加拿大"},
"YUL": {"name": "蒙特利尔", "region": "北美", "country": "加拿大"},
# 欧洲地区 - 西欧
"LHR": {"name": "伦敦", "region": "欧洲", "country": "英国"},
"CDG": {"name": "巴黎", "region": "欧洲", "country": "法国"},
"FRA": {"name": "法兰克福", "region": "欧洲", "country": "德国"},
"AMS": {"name": "阿姆斯特丹", "region": "欧洲", "country": "荷兰"},
"BRU": {"name": "布鲁塞尔", "region": "欧洲", "country": "比利时"},
"ZRH": {"name": "苏黎世", "region": "欧洲", "country": "瑞士"},
"VIE": {"name": "维也纳", "region": "欧洲", "country": "奥地利"},
"MUC": {"name": "慕尼黑", "region": "欧洲", "country": "德国"},
"DUS": {"name": "杜塞尔多夫", "region": "欧洲", "country": "德国"},
"HAM": {"name": "汉堡", "region": "欧洲", "country": "德国"},
# 欧洲地区 - 南欧
"MAD": {"name": "马德里", "region": "欧洲", "country": "西班牙"},
"BCN": {"name": "巴塞罗那", "region": "欧洲", "country": "西班牙"},
"MXP": {"name": "米兰", "region": "欧洲", "country": "意大利"},
"FCO": {"name": "罗马", "region": "欧洲", "country": "意大利"},
"ATH": {"name": "雅典", "region": "欧洲", "country": "希腊"},
"LIS": {"name": "里斯本", "region": "欧洲", "country": "葡萄牙"},
# 欧洲地区 - 北欧
"ARN": {"name": "斯德哥尔摩", "region": "欧洲", "country": "瑞典"},
"CPH": {"name": "哥本哈根", "region": "欧洲", "country": "丹麦"},
"OSL": {"name": "奥斯陆", "region": "欧洲", "country": "挪威"},
"HEL": {"name": "赫尔辛基", "region": "欧洲", "country": "芬兰"},
# 欧洲地区 - 东欧
"WAW": {"name": "华沙", "region": "欧洲", "country": "波兰"},
"PRG": {"name": "布拉格", "region": "欧洲", "country": "捷克"},
"BUD": {"name": "布达佩斯", "region": "欧洲", "country": "匈牙利"},
"OTP": {"name": "布加勒斯特", "region": "欧洲", "country": "罗马尼亚"},
"SOF": {"name": "索非亚", "region": "欧洲", "country": "保加利亚"},
# 中东地区
"DXB": {"name": "迪拜", "region": "中东", "country": "阿联酋"},
"TLV": {"name": "特拉维夫", "region": "中东", "country": "以色列"},
"BAH": {"name": "巴林", "region": "中东", "country": "巴林"},
"AMM": {"name": "安曼", "region": "中东", "country": "约旦"},
"KWI": {"name": "科威特", "region": "中东", "country": "科威特"},
"DOH": {"name": "多哈", "region": "中东", "country": "卡塔尔"},
"MCT": {"name": "马斯喀特", "region": "中东", "country": "阿曼"},
# 南美地区
"GRU": {"name": "圣保罗", "region": "南美", "country": "巴西"},
"GIG": {"name": "里约热内卢", "region": "南美", "country": "巴西"},
"EZE": {"name": "布宜诺斯艾利斯", "region": "南美", "country": "阿根廷"},
"BOG": {"name": "波哥大", "region": "南美", "country": "哥伦比亚"},
"LIM": {"name": "利马", "region": "南美", "country": "秘鲁"},
"SCL": {"name": "圣地亚哥", "region": "南美", "country": "智利"},
# 非洲地区
"JNB": {"name": "约翰内斯堡", "region": "非洲", "country": "南非"},
"CPT": {"name": "开普敦", "region": "非洲", "country": "南非"},
"CAI": {"name": "开罗", "region": "非洲", "country": "埃及"},
"LOS": {"name": "拉各斯", "region": "非洲", "country": "尼日利亚"},
"NBO": {"name": "内罗毕", "region": "非洲", "country": "肯尼亚"},
"ACC": {"name": "阿克拉", "region": "非洲", "country": "加纳"},
}
# 在线机场码列表URL(GitHub社区维护)
AIRPORT_CODES_URL = "https://raw.githubusercontent.com/cloudflare/cf-ui/master/packages/colo-config/src/data.json"
AIRPORT_CODES_FILE = "airport_codes.json"
# Cloudflare IP列表URL和文件
CLOUDFLARE_IP_URL = "https://www.cloudflare.com/ips-v4/"
CLOUDFLARE_IP_FILE = "Cloudflare.txt"
CLOUDFLARE_IPV6_URL = "https://www.cloudflare.com/ips-v6/"
CLOUDFLARE_IPV6_FILE = "Cloudflare_ipv6.txt"
# 默认测速URL
DEFAULT_SPEEDTEST_URL = "https://speed.cloudflare.com/__down?bytes=99999999"
# Cloudflare IPv6 地址段(内置)
# 数据来源:https://www.cloudflare.com/ips-v6/
CLOUDFLARE_IPV6_RANGES = [
# 主要地址段
"2400:cb00::/32",
"2606:4700::/32",
"2803:f800::/32",
"2405:b500::/32",
"2405:8100::/32",
"2a06:98c0::/29",
"2c0f:f248::/32",
# 详细子网段
"2400:cb00:2049::/48",
"2400:cb00:f00e::/48",
"2606:4700:10::/48",
"2606:4700:130::/48",
"2606:4700:3000::/48",
"2606:4700:3001::/48",
"2606:4700:3002::/48",
"2606:4700:3003::/48",
"2606:4700:3004::/48",
"2606:4700:3005::/48",
"2606:4700:3006::/48",
"2606:4700:3007::/48",
"2606:4700:3008::/48",
"2606:4700:3009::/48",
"2606:4700:3010::/48",
"2606:4700:3011::/48",
"2606:4700:3012::/48",
"2606:4700:3013::/48",
"2606:4700:3014::/48",
"2606:4700:3015::/48",
"2606:4700:3016::/48",
"2606:4700:3017::/48",
"2606:4700:3018::/48",
"2606:4700:3019::/48",
"2606:4700:3020::/48",
"2606:4700:3021::/48",
"2606:4700:3022::/48",
"2606:4700:3023::/48",
"2606:4700:3024::/48",
"2606:4700:3025::/48",
"2606:4700:3026::/48",
"2606:4700:3027::/48",
"2606:4700:3028::/48",
"2606:4700:3029::/48",
"2606:4700:3030::/48",
"2606:4700:3031::/48",
"2606:4700:3032::/48",
"2606:4700:3033::/48",
"2606:4700:3034::/48",
"2606:4700:3035::/48",
"2606:4700:3036::/48",
"2606:4700:3037::/48",
"2606:4700:3038::/48",
"2606:4700:3039::/48",
"2606:4700:a0::/48",
"2606:4700:a1::/48",
"2606:4700:a8::/48",
"2606:4700:a9::/48",
"2606:4700:a::/48",
"2606:4700:b::/48",
"2606:4700:c::/48",
"2606:4700:d0::/48",
"2606:4700:d1::/48",
"2606:4700:d::/48",
"2606:4700:e0::/48",
"2606:4700:e1::/48",
"2606:4700:e2::/48",
"2606:4700:e3::/48",
"2606:4700:e4::/48",
"2606:4700:e5::/48",
"2606:4700:e6::/48",
"2606:4700:e7::/48",
"2606:4700:e::/48",
"2606:4700:f1::/48",
"2606:4700:f2::/48",
"2606:4700:f3::/48",
"2606:4700:f4::/48",
"2606:4700:f5::/48",
"2606:4700:f::/48",
"2803:f800:50::/48",
"2803:f800:51::/48",
"2a06:98c1:3100::/48",
"2a06:98c1:3101::/48",
"2a06:98c1:3102::/48",
"2a06:98c1:3103::/48",
"2a06:98c1:3104::/48",
"2a06:98c1:3105::/48",
"2a06:98c1:3106::/48",
"2a06:98c1:3107::/48",
"2a06:98c1:3108::/48",
"2a06:98c1:3109::/48",
"2a06:98c1:310a::/48",
"2a06:98c1:310b::/48",
"2a06:98c1:310c::/48",
"2a06:98c1:310d::/48",
"2a06:98c1:310e::/48",
"2a06:98c1:310f::/48",
"2a06:98c1:3120::/48",
"2a06:98c1:3121::/48",
"2a06:98c1:3122::/48",
"2a06:98c1:3123::/48",
"2a06:98c1:3200::/48",
"2a06:98c1:50::/48",
"2a06:98c1:51::/48",
"2a06:98c1:54::/48",
"2a06:98c1:58::/48",
]
# GitHub Release版本 - 使用官方CloudflareSpeedTest
GITHUB_VERSION = "v2.3.4"
GITHUB_REPO = "XIU2/CloudflareSpeedTest"
# 配置文件路径
CONFIG_FILE = ".cloudflare_speedtest_config.json"
# 保存交互模式下生成的命令(用于定时任务)
LAST_GENERATED_COMMAND = None
def generate_ipv6_file():
"""生成 IPv6 地址列表文件"""
try:
with open(CLOUDFLARE_IPV6_FILE, 'w', encoding='utf-8') as f:
for ipv6_range in CLOUDFLARE_IPV6_RANGES:
f.write(ipv6_range + '\n')
print(f"✅ IPv6 地址列表已生成: {CLOUDFLARE_IPV6_FILE}")
print(f" 共 {len(CLOUDFLARE_IPV6_RANGES)} 个 IPv6 地址段")
return True
except Exception as e:
print(f"❌ 生成 IPv6 地址列表失败: {e}")
return False
def get_system_info():
"""获取系统信息"""
system = platform.system().lower()
machine = platform.machine().lower()
# 标准化系统名称
if system == "darwin":
os_type = "darwin"
elif system == "linux":
os_type = "linux"
elif system == "windows":
os_type = "win"
else:
print(f"不支持的操作系统: {system}")
if sys.platform == "win32":
input("按 Enter 键退出...")
sys.exit(1)
# 标准化架构名称
if machine in ["x86_64", "amd64", "x64"]:
arch_type = "amd64"
elif machine in ["arm64", "aarch64"]:
arch_type = "arm64"
elif machine in ["armv7l", "armv6l"]:
arch_type = "arm"
else:
print(f"不支持的架构: {machine}")
if sys.platform == "win32":
input("按 Enter 键退出...")
sys.exit(1)
return os_type, arch_type
def get_executable_name(os_type, arch_type):
"""获取可执行文件名 - 使用官方命名规则"""
if os_type == "win":
return f"CloudflareST_windows_{arch_type}.exe"
elif os_type == "darwin":
return f"CloudflareST_darwin_{arch_type}"
else: # linux
return f"CloudflareST_linux_{arch_type}"
def download_file(url, filename):
"""下载文件 - 支持多种下载方法"""
print(f"正在下载: {url}")
# 方法1: 尝试使用 requests(SSL不可用时静默切换到curl)
try:
try:
response = requests.get(url, stream=True, timeout=60)
response.raise_for_status()
with open(filename, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"✅ 下载完成: {filename}")
return True
except ImportError as e:
# SSL模块不可用,静默切换到curl下载
if "SSL module is not available" in str(e):
result = subprocess.run([
"curl", "-L", "-o", filename, url
], capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=60)
if result.returncode == 0 and os.path.exists(filename):
print(f"✅ 下载完成: {filename}")
return True
else:
raise
except Exception:
# 静默失败,继续尝试其他方法
pass
# 方法2: 尝试使用 wget
try:
result = subprocess.run([
"wget", "-O", filename, url
], capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=60)
if result.returncode == 0 and os.path.exists(filename):
print(f"✅ 下载完成: {filename}")
return True
except (subprocess.TimeoutExpired, FileNotFoundError):
# wget 不可用,静默继续
pass
except Exception:
# wget 执行失败,静默继续
pass
# 方法3: 尝试使用 curl
try:
result = subprocess.run([
"curl", "-L", "-o", filename, url
], capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=60)
if result.returncode == 0 and os.path.exists(filename):
print(f"✅ 下载完成: {filename}")
return True
except (subprocess.TimeoutExpired, FileNotFoundError):
# curl 不可用,静默继续
pass
except Exception:
# curl 执行失败,静默继续
pass
# 方法3.5: Windows PowerShell 下载
if sys.platform == "win32":
try:
ps_cmd = f'Invoke-WebRequest -Uri "{url}" -OutFile "{filename}"'
result = subprocess.run([
"powershell", "-Command", ps_cmd
], capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=60)
if result.returncode == 0 and os.path.exists(filename):
print(f"✅ 下载完成: {filename}")
return True
except (subprocess.TimeoutExpired, FileNotFoundError):
# PowerShell 不可用,静默继续
pass
except Exception:
# PowerShell 执行失败,静默继续
pass
# 方法4: 尝试使用 urllib
try:
import urllib.request
urllib.request.urlretrieve(url, filename)
print(f"✅ 下载完成: {filename}")
return True
except Exception:
# urllib 下载失败,静默继续
pass
# 方法5: 尝试 HTTP 版本
if url.startswith("https://"):
http_url = url.replace("https://", "http://")
try:
try:
response = requests.get(http_url, stream=True, timeout=60)
response.raise_for_status()
with open(filename, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"✅ 下载完成: {filename}")
return True
except ImportError as e:
# SSL模块不可用,静默切换到curl下载
if "SSL module is not available" in str(e):
result = subprocess.run([
"curl", "-L", "-o", filename, http_url
], capture_output=True, text=True, timeout=60)
if result.returncode == 0 and os.path.exists(filename):
print(f"✅ 下载完成: {filename}")
return True
else:
raise
except Exception:
# HTTP 下载失败,静默继续
pass
# 所有方法都失败
print("❌ 下载失败")
return False
def download_cloudflare_speedtest(os_type, arch_type):
"""下载 CloudflareSpeedTest 可执行文件(优先使用反代版本)"""
# 优先检查反代版本
if os_type == "win":
proxy_exec_name = f"CloudflareST_proxy_{os_type}_{arch_type}.exe"
else:
proxy_exec_name = f"CloudflareST_proxy_{os_type}_{arch_type}"
if os.path.exists(proxy_exec_name):
print(f"✓ 使用反代版本: {proxy_exec_name}")
return proxy_exec_name
# 检查是否已下载反代版本
print("反代版本不存在,开始下载反代版本...")
# 构建下载URL - 使用您的GitHub仓库
if os_type == "win":
if arch_type == "amd64":
archive_name = "CloudflareST_proxy_windows_amd64.zip"
else:
archive_name = "CloudflareST_proxy_windows_386.zip"
elif os_type == "darwin":
if arch_type == "amd64":
archive_name = "CloudflareST_proxy_darwin_amd64.zip"
else:
archive_name = "CloudflareST_proxy_darwin_arm64.zip"
else: # linux
if arch_type == "amd64":
archive_name = "CloudflareST_proxy_linux_amd64.tar.gz"
elif arch_type == "386":
archive_name = "CloudflareST_proxy_linux_386.tar.gz"
else: # arm64
archive_name = "CloudflareST_proxy_linux_arm64.tar.gz"
download_url = f"https://github.com/byJoey/CloudflareSpeedTest/releases/download/v1.0/{archive_name}"
if not download_file(download_url, archive_name):
# 备用方案: 尝试 HTTP 下载
http_url = download_url.replace("https://", "http://")
if not download_file(http_url, archive_name):
# 所有自动下载都失败,提供手动下载说明
print("\n" + "="*60)
print("自动下载失败,请手动下载反代版本:")
print(f"下载地址: {download_url}")
print(f"解压后文件名应为: CloudflareST_proxy_{os_type}_{arch_type}{'.exe' if os_type == 'win' else ''}")
print("="*60)
# 检查是否有手动下载的反代版本文件
if os_type == "win":
proxy_exec_name = f"CloudflareST_proxy_{os_type}_{arch_type}.exe"
else:
proxy_exec_name = f"CloudflareST_proxy_{os_type}_{arch_type}"
if os.path.exists(proxy_exec_name):
print(f"找到手动下载的反代版本: {proxy_exec_name}")
# 手动下载的文件也需要赋予执行权限
if os_type != "win":
os.chmod(proxy_exec_name, 0o755)
print(f"已赋予执行权限: {proxy_exec_name}")
return proxy_exec_name
else:
print("未找到反代版本文件,程序无法继续")
if sys.platform == "win32":
input("按 Enter 键退出...")
sys.exit(1)
else:
# 解压文件
print(f"正在解压: {archive_name}")
try:
if archive_name.endswith('.zip'):
import zipfile
with zipfile.ZipFile(archive_name, 'r') as zip_ref:
zip_ref.extractall('.')
elif archive_name.endswith('.tar.gz'):
import tarfile
with tarfile.open(archive_name, 'r:gz') as tar_ref:
tar_ref.extractall('.')
# 查找反代版本可执行文件
found_executable = None
for root, dirs, files in os.walk('.'):
for file in files:
if file.startswith('CloudflareST_proxy_') and not file.endswith(('.zip', '.tar.gz')):
found_executable = os.path.join(root, file)
break
if found_executable:
break
if found_executable:
# 获取最终文件名 - 使用标准格式
if os_type == "win":
final_name = f"CloudflareST_proxy_{os_type}_{arch_type}.exe"
else:
final_name = f"CloudflareST_proxy_{os_type}_{arch_type}"
# 如果文件不在当前目录或文件名不匹配,移动到当前目录并重命名
if os.path.abspath(found_executable) != os.path.abspath(final_name):
if os.path.exists(final_name):
os.remove(final_name)
# 确保源文件存在
if os.path.exists(found_executable):
os.rename(found_executable, final_name)
else:
print(f"❌ 源文件不存在: {found_executable}")
if sys.platform == "win32":
input("按 Enter 键退出...")
sys.exit(1)
# 设置执行权限
if os_type != "win":
os.chmod(final_name, 0o755)
print(f"✓ 反代版本设置完成: {final_name}")
return final_name
else:
print("解压后未找到反代版本可执行文件")
# 列出解压后的所有文件用于调试
print("解压后的文件:")
for root, dirs, files in os.walk('.'):
for file in files:
if not file.endswith(('.zip', '.tar.gz', '.txt', '.md')):
print(f" - {os.path.join(root, file)}")
if sys.platform == "win32":
input("按 Enter 键退出...")
sys.exit(1)
# 清理压缩包
os.remove(archive_name)
except Exception as e:
print(f"解压失败: {e}")
if sys.platform == "win32":
input("按 Enter 键退出...")
sys.exit(1)
# 在Unix系统上赋予执行权限
if os_type != "win":
os.chmod(proxy_exec_name, 0o755)
print(f"已赋予执行权限: {proxy_exec_name}")
return proxy_exec_name
def select_ip_version():
"""选择IP版本(IPv4或IPv6)"""
print("\n" + "=" * 60)
print(" IP 版本选择")
print("=" * 60)
print(" 1. IPv4 - 测试 IPv4 地址(推荐,兼容性最好)")
print(" 2. IPv6 - 测试 IPv6 地址(需要本地网络支持IPv6)")
print("=" * 60)
while True:
choice = input("\n请选择 IP 版本 [1/2,默认:1]: ").strip()
if not choice or choice == "1":
print("✓ 已选择: IPv4")
return "ipv4", CLOUDFLARE_IP_FILE
elif choice == "2":
print("✓ 已选择: IPv6")
return "ipv6", CLOUDFLARE_IPV6_FILE
else:
print("✗ 请输入 1 或 2")
def download_cloudflare_ips(ip_version="ipv4", ip_file=CLOUDFLARE_IP_FILE):
"""下载或生成 Cloudflare IP 列表
Args:
ip_version: IP版本 ("ipv4" 或 "ipv6")
ip_file: IP文件路径
"""
# 检查文件是否已存在
if os.path.exists(ip_file):
print(f"✅ 使用已有IP文件: {ip_file}")
return True
if ip_version == "ipv6":
# IPv6 使用内置地址段生成
print("正在生成 Cloudflare IPv6 地址列表...")
return generate_ipv6_file()
else:
# IPv4 从网络下载
print("正在下载 Cloudflare IPv4 列表...")
if not download_file(CLOUDFLARE_IP_URL, CLOUDFLARE_IP_FILE):
print("下载 Cloudflare IP 列表失败")
return False
# 检查文件是否为空
if os.path.getsize(CLOUDFLARE_IP_FILE) == 0:
print("Cloudflare IP 列表文件为空")
return False
print(f"Cloudflare IP 列表已保存到: {CLOUDFLARE_IP_FILE}")
return True
def load_local_airport_codes():
"""从本地文件加载机场码(如果存在)"""
if os.path.exists(AIRPORT_CODES_FILE):
try:
with open(AIRPORT_CODES_FILE, 'r', encoding='utf-8') as f:
custom_codes = json.load(f)
AIRPORT_CODES.update(custom_codes)
print(f"✓ 已加载本地机场码配置({len(custom_codes)} 个)")
except Exception as e:
print(f"加载本地机场码失败: {e}")
def save_airport_codes():
"""保存机场码到本地文件"""
try:
with open(AIRPORT_CODES_FILE, 'w', encoding='utf-8') as f:
json.dump(AIRPORT_CODES, f, ensure_ascii=False, indent=2)
print(f"✓ 机场码已保存到: {AIRPORT_CODES_FILE}")
except Exception as e:
print(f"保存机场码失败: {e}")
def display_airport_codes(region_filter=None):
"""显示所有支持的机场码,可按地区筛选"""
# 按地区分组
regions = {}
for code, info in AIRPORT_CODES.items():
region = info.get('region', '其他')
if region not in regions:
regions[region] = []
regions[region].append((code, info))
# 显示统计信息
print(f"\n支持的机场码列表(共 {len(AIRPORT_CODES)} 个数据中心)")
print("=" * 70)
# 如果指定了地区筛选
if region_filter:
region_filter = region_filter.strip()
if region_filter in regions:
print(f"\n【{region_filter}地区】")
print("-" * 70)
for code, info in sorted(regions[region_filter], key=lambda x: x[0]):
country = info.get('country', '')
print(f" {code:5s} - {info['name']:20s} ({country})")
else:
print(f"未找到地区: {region_filter}")
print(f"可用地区: {', '.join(sorted(regions.keys()))}")
return
# 显示所有地区
region_order = ["亚太", "北美", "欧洲", "中东", "南美", "非洲", "其他"]
for region in region_order:
if region in regions:
print(f"\n【{region}地区】({len(regions[region])} 个)")
print("-" * 70)
for code, info in sorted(regions[region], key=lambda x: x[0]):
country = info.get('country', '')
print(f" {code:5s} - {info['name']:20s} ({country})")
print("=" * 70)
def display_popular_codes():
"""显示热门机场码"""
popular = {
"HKG": "香港", "SIN": "新加坡", "NRT": "东京成田", "ICN": "首尔",
"LAX": "洛杉矶", "SJC": "圣何塞", "LHR": "伦敦", "FRA": "法兰克福"
}
print("\n热门机场码:")
print("-" * 50)
for code, name in popular.items():
if code in AIRPORT_CODES:
info = AIRPORT_CODES[code]
region = info.get('region', '')
print(f" {code:5s} - {name:15s} [{region}]")
print("-" * 50)
def find_airport_by_name(query):
"""根据城市名称查找机场码(支持模糊匹配)"""
query = query.strip()
if not query:
return None
# 先尝试精确匹配机场码
query_upper = query.upper()
if query_upper in AIRPORT_CODES:
return query_upper
# 构建城市名称到机场码的映射
results = []
for code, info in AIRPORT_CODES.items():
name = info.get('name', '').lower()
country = info.get('country', '').lower()
query_lower = query.lower()
# 精确匹配城市名称
if name == query_lower:
return code
# 模糊匹配(包含关系)
if query_lower in name or name in query_lower:
results.append((code, info, 1)) # 优先级1
elif query_lower in country:
results.append((code, info, 2)) # 优先级2
# 如果有匹配结果
if results:
# 按优先级排序
results.sort(key=lambda x: x[2])
# 如果只有一个结果,直接返回
if len(results) == 1:
return results[0][0]
# 如果有多个结果,显示让用户选择
print(f"\n找到 {len(results)} 个匹配的城市:")
print("-" * 60)
for idx, (code, info, _) in enumerate(results[:10], 1): # 最多显示10个
region = info.get('region', '')
country = info.get('country', '')
print(f" {idx}. {code:5s} - {info['name']:20s} ({country}) [{region}]")
print("-" * 60)
try:
choice = input(f"\n请选择 [1-{min(len(results), 10)}] 或按回车取消: ").strip()
if choice:
idx = int(choice) - 1
if 0 <= idx < min(len(results), 10):
return results[idx][0]
except (ValueError, IndexError):
pass
return None
def display_preset_configs():
"""显示预设配置"""
print("\n" + "=" * 60)
print(" 预设配置选项")
print("=" * 60)
print(" 1. 快速测试 (10个IP, 1MB/s, 1000ms)")
print(" 2. 标准测试 (20个IP, 2MB/s, 500ms)")
print(" 3. 高质量测试 (50个IP, 5MB/s, 200ms)")
print(" 4. 自定义配置")
print("=" * 60)
def get_user_input(ip_file=CLOUDFLARE_IP_FILE, ip_version="ipv4"):
"""获取用户输入参数
Args:
ip_file: 要使用的IP文件路径
ip_version: IP版本("ipv4" 或 "ipv6")
"""
# 询问功能选择
print("\n" + "=" * 60)
print(" 功能选择")
print("=" * 60)
print(" 1. 小白快速测试 - 简单输入,适合新手")
print(" 2. 常规测速 - 测试指定机场码的IP速度(支持多地区同时测速)")
print(" 3. 优选反代 - 从CSV文件生成反代IP列表")
print("=" * 60)
choice = input("\n请选择功能 [默认: 1]: ").strip()
if not choice:
choice = "1"
if choice == "1":
# 小白快速测试模式
return handle_beginner_mode(ip_file, ip_version)
elif choice == "3":
# 优选反代模式
return handle_proxy_mode()
else:
# 常规测速模式
return handle_normal_mode(ip_file, ip_version)
def select_csv_file():
"""选择CSV文件"""
while True:
csv_file = input("\n请输入CSV文件路径 [默认: result.csv]: ").strip()
if not csv_file:
csv_file = "result.csv"
if os.path.exists(csv_file):
print(f"找到文件: {csv_file}")
return csv_file
else:
print(f"文件不存在: {csv_file}")
print("请确保文件路径正确,或先运行常规测速生成result.csv")
retry = input("是否重新输入?[Y/n]: ").strip().lower()
if retry in ['n', 'no']:
return None
def handle_proxy_mode():
"""处理优选反代模式"""
print("\n" + "=" * 70)
print(" 优选反代模式")
print("=" * 70)
print(" 此功能将从CSV文件中提取IP和端口信息,生成反代IP列表")
print(" CSV文件格式要求:")
print(" - 包含 'IP 地址' 和 '端口' 列")
print(" - 或包含 'ip' 和 'port' 列")
print(" - 支持逗号分隔的CSV格式")
print("=" * 70)
# 选择CSV文件
csv_file = select_csv_file()
if not csv_file:
print("未选择有效文件,退出优选反代模式")
return None, None, None, None
# 生成反代IP列表
print(f"\n正在处理CSV文件: {csv_file}")
success = generate_proxy_list(csv_file, "ips_ports.txt")
if success:
print("\n" + "=" * 60)
print(" 优选反代功能完成!")
print("=" * 60)
print(" 生成的文件:")
print(" - ips_ports.txt (反代IP列表)")
print(" - 格式: IP:端口 (每行一个)")
print("\n 使用说明:")
print(" - 可直接用于反代配置")
print(" - 支持各种代理软件")
print(" - 建议定期更新IP列表")
print("=" * 60)
# 询问是否进行测速
print("\n" + "=" * 50)
test_choice = input("是否对反代IP列表进行测速?[Y/n]: ").strip().lower()
if test_choice in ['n', 'no']:
print("跳过测速,优选反代功能完成")
return None, None, None, None
print("开始对反代IP列表进行测速...")
print("注意: 反代模式直接对IP列表测速,不需要选择机场码")
# 显示预设配置选项
display_preset_configs()
# 获取配置选择
while True:
config_choice = input("\n请选择配置 [默认: 1]: ").strip()
if not config_choice:
config_choice = "1"