forked from ntbowen/yx-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudflare_speedtest.py
More file actions
4711 lines (4085 loc) · 187 KB
/
cloudflare_speedtest.py
File metadata and controls
4711 lines (4085 loc) · 187 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
def get_app_data_dir():
"""
获取应用数据目录(用于存放下载的可执行文件等)
在打包后的应用中,当前目录可能是只读的,需要使用用户数据目录
"""
app_name = "yx-tools"
if sys.platform == "darwin":
# macOS: ~/Library/Application Support/yx-tools
base = os.path.expanduser("~/Library/Application Support")
elif sys.platform == "win32":
# Windows: %APPDATA%/yx-tools
base = os.environ.get("APPDATA", os.path.expanduser("~"))
else:
# Linux: ~/.local/share/yx-tools
base = os.environ.get("XDG_DATA_HOME", os.path.expanduser("~/.local/share"))
app_dir = os.path.join(base, app_name)
# 确保目录存在
try:
os.makedirs(app_dir, exist_ok=True)
except Exception:
# 如果创建失败,回退到当前目录
app_dir = os.getcwd()
return app_dir
# 使用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?measId=&bytes=200000000"
# 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
# Cloudflare 支持的 HTTPS 端口列表
# 参考: https://developers.cloudflare.com/fundamentals/reference/network-ports/
CLOUDFLARE_HTTPS_PORTS = [443, 8443, 2053, 2083, 2087, 2096]
# 测速 URL 配置
# 默认 URL(可能不支持多端口下载测速)
DEFAULT_SPEEDTEST_URL = "https://cf.xiu2.xyz/url"
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 可执行文件(优先使用反代版本)"""
# 获取应用数据目录(用于存放下载的可执行文件)
app_data_dir = get_app_data_dir()
# 构建可执行文件名
if os_type == "win":
exec_basename = f"CloudflareST_proxy_{os_type}_{arch_type}.exe"
else:
exec_basename = f"CloudflareST_proxy_{os_type}_{arch_type}"
# 完整路径
proxy_exec_path = os.path.join(app_data_dir, exec_basename)
# 优先检查应用数据目录中的反代版本
if os.path.exists(proxy_exec_path):
# 确保有执行权限
if os_type != "win":
try:
os.chmod(proxy_exec_path, 0o755)
except Exception:
pass
print(f"✓ 使用反代版本: {proxy_exec_path}")
return proxy_exec_path
# 也检查当前目录(兼容旧版本)
if os.path.exists(exec_basename):
if os_type != "win":
try:
os.chmod(exec_basename, 0o755)
except Exception:
pass
print(f"✓ 使用反代版本: {exec_basename}")
return os.path.abspath(exec_basename)
# 检查是否已下载反代版本
print(f"反代版本不存在,开始下载反代版本到 {app_data_dir}...")
# 构建下载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}"
# 下载到应用数据目录
archive_path = os.path.join(app_data_dir, archive_name)
if not download_file(download_url, archive_path):
# 备用方案: 尝试 HTTP 下载
http_url = download_url.replace("https://", "http://")
if not download_file(http_url, archive_path):
# 所有自动下载都失败,提供手动下载说明
print("\n" + "="*60)
print("自动下载失败,请手动下载反代版本:")
print(f"下载地址: {download_url}")
print(f"解压后放到: {app_data_dir}")
print(f"文件名应为: {exec_basename}")
print("="*60)
# 检查是否有手动下载的反代版本文件
if os.path.exists(proxy_exec_path):
print(f"找到手动下载的反代版本: {proxy_exec_path}")
if os_type != "win":
os.chmod(proxy_exec_path, 0o755)
print(f"已赋予执行权限: {proxy_exec_path}")
return proxy_exec_path
else:
print("未找到反代版本文件,程序无法继续")
if sys.platform == "win32":
input("按 Enter 键退出...")
sys.exit(1)
else:
# 解压文件到应用数据目录
print(f"正在解压: {archive_path}")
try:
if archive_name.endswith('.zip'):
import zipfile
with zipfile.ZipFile(archive_path, 'r') as zip_ref:
zip_ref.extractall(app_data_dir)
elif archive_name.endswith('.tar.gz'):
import tarfile
with tarfile.open(archive_path, 'r:gz') as tar_ref:
tar_ref.extractall(app_data_dir)
# 查找反代版本可执行文件
found_executable = None
for root, dirs, files in os.walk(app_data_dir):
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.path.abspath(found_executable) != os.path.abspath(proxy_exec_path):
if os.path.exists(proxy_exec_path):
os.remove(proxy_exec_path)
if os.path.exists(found_executable):
os.rename(found_executable, proxy_exec_path)
else:
print(f"❌ 源文件不存在: {found_executable}")
if sys.platform == "win32":
input("按 Enter 键退出...")
sys.exit(1)
# 设置执行权限
if os_type != "win":
os.chmod(proxy_exec_path, 0o755)
# 清理压缩包
try:
os.remove(archive_path)
except Exception:
pass
print(f"✓ 反代版本设置完成: {proxy_exec_path}")
return proxy_exec_path
else:
print("解压后未找到反代版本可执行文件")
print("解压后的文件:")
for root, dirs, files in os.walk(app_data_dir):
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)
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_path, 0o755)
print(f"已赋予执行权限: {proxy_exec_path}")
return proxy_exec_path
def get_exec_cmd(exec_name):
"""
获取可执行文件的命令路径
如果是绝对路径直接返回,否则在 Unix 系统上添加 ./ 前缀
"""
if os.path.isabs(exec_name):
return exec_name
elif sys.platform == "win32":
return exec_name
else:
return f"./{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 select_ports():
"""选择要测试的端口"""
print("\n" + "=" * 60)
print(" 端口选择")
print("=" * 60)
print(" Cloudflare 支持的 HTTPS 端口:")
for i, port in enumerate(CLOUDFLARE_HTTPS_PORTS, 1):
default_mark = " (默认)" if port == 443 else ""
print(f" {i}. {port}{default_mark}")
print(f" {len(CLOUDFLARE_HTTPS_PORTS) + 1}. 全部端口 - 测试所有支持的端口")
print(f" {len(CLOUDFLARE_HTTPS_PORTS) + 2}. 自定义 - 手动选择多个端口")
print("=" * 60)
print("💡 提示: 尽量使用单端口, 多端口会大大增加测试时间")
while True:
choice = input(f"\n请选择端口 [1-{len(CLOUDFLARE_HTTPS_PORTS) + 2}, 默认: 1]: ").strip()
if not choice or choice == "1":
print("✓ 已选择端口: 443")
return [443]
try:
choice_int = int(choice)
if 1 <= choice_int <= len(CLOUDFLARE_HTTPS_PORTS):
selected_port = CLOUDFLARE_HTTPS_PORTS[choice_int - 1]
print(f"✓ 已选择端口: {selected_port}")
return [selected_port]
elif choice_int == len(CLOUDFLARE_HTTPS_PORTS) + 1:
print(f"✓ 已选择全部端口: {', '.join(map(str, CLOUDFLARE_HTTPS_PORTS))}")
return CLOUDFLARE_HTTPS_PORTS.copy()
elif choice_int == len(CLOUDFLARE_HTTPS_PORTS) + 2:
# 自定义选择多个端口
# 使用单字节逗号显示,方便用户复制
ports_str = ','.join(map(str, CLOUDFLARE_HTTPS_PORTS))
print(f"\n请输入要测试的端口号, 用逗号分隔 (可直接复制下方端口)")
print(f"可选端口: {ports_str}")
custom_input = input("端口列表: ").strip()
if custom_input:
selected_ports = []
# 同时支持中英文逗号
for p in custom_input.replace(',', ',').split(','):
p = p.strip()
if p.isdigit():
port_int = int(p)
if port_int in CLOUDFLARE_HTTPS_PORTS:
if port_int not in selected_ports:
selected_ports.append(port_int)
else:
print(f"⚠️ 端口 {port_int} 不在 Cloudflare 支持列表中, 已跳过")
if selected_ports:
print(f"✓ 已选择端口: {', '.join(map(str, selected_ports))}")
return selected_ports
else:
print("✗ 未选择有效端口, 请重新选择")
else:
print("✗ 输入为空, 请重新选择")
else:
print(f"✗ 请输入 1-{len(CLOUDFLARE_HTTPS_PORTS) + 2} 之间的数字")
except ValueError:
print("✗ 请输入有效的数字")
def select_speedtest_url():
"""选择测速 URL"""
# 尝试读取上次保存的自定义 URL
saved_url = None
config = load_config()
if config and config.get("speedtest_url"):
saved_url = config.get("speedtest_url")
print("\n" + "=" * 60)
print(" 测速 URL 选择")
print("=" * 60)
print(" 1. 默认 URL - cf.xiu2.xyz (可能不支持多端口)")
if saved_url:
print(f" 2. 上次使用 - {saved_url}")
print(" 3. 自定义 URL - 输入新的测速地址")
else:
print(" 2. 自定义 URL - 输入自建测速地址 (可根据 URL 特性确认是否支持多端口)")
print("=" * 60)
while True:
if saved_url:
choice = input("\n请选择 [1/2/3, 默认: 2]: ").strip()
if not choice or choice == "2":
print(f"✓ 使用上次的测速 URL: {saved_url}")
return saved_url
elif choice == "1":
print(f"✓ 使用默认测速 URL: {DEFAULT_SPEEDTEST_URL}")
print("⚠️ 注意: 默认 URL 可能不支持多端口, 非 443 端口下载测速可能失败")
return DEFAULT_SPEEDTEST_URL
elif choice == "3":
custom_url = input("请输入自定义测速 URL (https://...): ").strip()
if custom_url:
if not custom_url.startswith("http"):
custom_url = "https://" + custom_url
print(f"✓ 使用自定义测速 URL: {custom_url}")
# 保存到配置文件
save_config(speedtest_url=custom_url)
return custom_url
else:
print("✗ URL 不能为空, 请重新输入")
else:
print("✗ 请输入 1, 2 或 3")
else:
choice = input("\n请选择 [1/2, 默认: 1]: ").strip()
if not choice or choice == "1":
print(f"✓ 使用默认测速 URL: {DEFAULT_SPEEDTEST_URL}")
print("⚠️ 注意: 默认 URL 可能不支持多端口, 非 443 端口下载测速可能失败")
return DEFAULT_SPEEDTEST_URL
elif choice == "2":
custom_url = input("请输入自定义测速 URL (https://...): ").strip()
if custom_url:
if not custom_url.startswith("http"):
custom_url = "https://" + custom_url
print(f"✓ 使用自定义测速 URL: {custom_url}")
# 保存到配置文件
save_config(speedtest_url=custom_url)
return custom_url
else:
print("✗ URL 不能为空, 请重新输入")
else:
print("✗ 请输入 1 或 2")
def generate_ip_with_ports(ip_file, ports, output_file="ip_with_ports.txt"):
"""根据 IP 文件和端口列表生成带端口的 IP 文件
CloudflareSpeedTest 支持的格式:
- 单个 IP: 1.2.3.4:443
- CIDR 格式需要使用 -tp 参数指定端口,不能在 IP 后面加端口
Args:
ip_file: 原始 IP 文件路径
ports: 端口列表
output_file: 输出文件路径
Returns:
tuple: (输出文件路径, 端口列表) 或 (None, None) 失败时
"""
if not os.path.exists(ip_file):
print(f"❌ IP 文件不存在: {ip_file}")
return None, None
try:
# 读取原始 IP 列表
with open(ip_file, 'r', encoding='utf-8') as f:
ips = [line.strip() for line in f if line.strip()]
if not ips:
print("❌ IP 文件为空")
return None, None
# 检查是否包含 CIDR 格式
has_cidr = any('/' in ip for ip in ips)
if has_cidr:
# CIDR 格式不能在 IP 后面加端口,需要使用 -tp 参数
# 直接复制原文件,返回端口列表供命令行使用
print(f"📝 检测到 CIDR 格式,将使用 -tp 参数指定端口")
# 复制原文件到输出文件
with open(output_file, 'w', encoding='utf-8') as f:
for ip in ips:
f.write(ip + '\n')
print(f"✅ IP 文件已准备: {output_file}")
print(f" IP/CIDR 数量: {len(ips)}")
print(f" 测试端口: {', '.join(map(str, ports))}")
return output_file, ports
else:
# 单个 IP 格式,可以在 IP 后面加端口
ip_port_list = []
for ip in ips:
# 如果 IP 已经包含端口,跳过
if ':' in ip and not ip.startswith('['): # IPv4:port 格式
ip_port_list.append(ip)
elif ip.startswith('[') and ']:' in ip: # [IPv6]:port 格式
ip_port_list.append(ip)
else:
# 为每个端口生成一条记录
for port in ports:
if ':' in ip: # IPv6 地址
ip_port_list.append(f"[{ip}]:{port}")
else: # IPv4 地址
ip_port_list.append(f"{ip}:{port}")
# 写入输出文件
with open(output_file, 'w', encoding='utf-8') as f:
for ip_port in ip_port_list:
f.write(ip_port + '\n')
print(f"✅ 已生成带端口的 IP 文件: {output_file}")
print(f" 原始 IP 数量: {len(ips)}")
print(f" 端口数量: {len(ports)}")
print(f" 生成记录数: {len(ip_port_list)}")
return output_file, None # 端口已在文件中,不需要 -tp 参数
except Exception as e:
print(f"❌ 生成带端口 IP 文件失败: {e}")
return None, None
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