-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsetHosts_Classic.py
1910 lines (1714 loc) · 68.4 KB
/
setHosts_Classic.py
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
import argparse
import asyncio
import concurrent
import ctypes
import json
import logging
import logging.config
import os
import platform
import re
import shutil
import socket
import ssl
import sys
from datetime import datetime, timedelta, timezone
from enum import Enum
from functools import wraps
from math import floor
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple
import dns.resolver
import httpx
import wcwidth
from rich import print as rprint
# from rich.progress import Progress, SpinnerColumn, TextColumn
# -------------------- 常量设置 -------------------- #
RESOLVER_TIMEOUT = 0.1 # DNS 解析超时时间 秒
HOSTS_NUM = 1 # 每个域名限定Hosts主机 ipv4 数量
MAX_LATENCY = 500 # 允许的最大延迟
PING_TIMEOUT = 1 # ping 超时时间
NUM_PINGS = 4 # ping次数
# 初始化日志模块
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
# -------------------- 解析参数 -------------------- #
def parse_args():
parser = argparse.ArgumentParser(
description=(
"------------------------------------------------------------\n"
"Hosts文件更新工具,此工具可自动解析域名并优化系统的hosts文件\n"
"------------------------------------------------------------\n"
),
epilog=(
"------------------------------------------------------------\n"
"项目: https://github.com/sinspired/cnNetTool\n"
"作者: Sinspired\n"
"邮箱: ggmomo@gmail.com\n"
"发布: 2024-12-06\n"
),
formatter_class=argparse.RawTextHelpFormatter, # 允许换行格式
)
parser.add_argument(
"-log",
default="info",
choices=["debug", "info", "warning", "error"],
help="设置日志输出等级",
)
parser.add_argument(
"-num",
"--hosts-num",
default=HOSTS_NUM,
type=int,
help="限定Hosts主机 ip 数量",
)
parser.add_argument(
"-max",
"--max-latency",
default=MAX_LATENCY,
type=int,
help="设置允许的最大延迟(毫秒)",
)
parser.add_argument(
"-v",
"--verbose",
action="store_true",
help="打印运行信息",
)
parser.add_argument(
"-size",
"--batch-size",
default=5,
type=int,
help="SSL证书验证批次",
)
parser.add_argument(
"-policy",
"--dns-resolve-policy",
default="all",
type=str,
help="DNS解析器区域选择,[all、global、china]",
)
return parser.parse_args()
args = parse_args()
logging.getLogger().setLevel(args.log.upper())
# -------------------- 辅助功能模块 -------------------- #
class Utils:
@staticmethod
def is_ipv6(ip: str) -> bool:
return ":" in ip
@staticmethod
def get_hosts_file_path() -> str:
os_type = platform.system().lower()
if os_type == "windows":
return r"C:\Windows\System32\drivers\etc\hosts"
elif os_type in ["linux", "darwin"]:
return "/etc/hosts"
else:
raise ValueError("不支持的操作系统")
@staticmethod
def backup_hosts_file(hosts_file_path: str):
if os.path.exists(hosts_file_path):
backup_path = f"{hosts_file_path}.bak"
shutil.copy(hosts_file_path, backup_path)
rprint(
f"\n[blue]已备份 [underline]{hosts_file_path}[/underline] 到 [underline]{backup_path}[/underline][/blue]"
)
@staticmethod
def write_readme_file(
hosts_content: List[str], temp_file_path: str, update_time: str
):
"""
根据模板文件生成 README.md 文件,并将 hosts 文件内容写入其中。
参数:
hosts_content (List[str]): hosts 文件的内容,以列表形式传入
temp_file_path (str): 输出的 README.md 文件路径
update_time (str): hosts 文件的更新时间,格式为 "YYYY-MM-DD HH:MM:SS +0800"
"""
try:
# 获取template文件的绝对路径
current_dir = os.path.dirname(os.path.abspath(__file__))
template_path = os.path.join(current_dir, temp_file_path)
if not os.path.exists(template_path):
raise FileNotFoundError(f"模板文件未找到: {template_path}")
# 读取模板文件
with open(template_path, "r", encoding="utf-8") as temp_fb:
template_content = temp_fb.read()
# 将hosts内容转换为字符串
hosts_str = "\n".join(hosts_content)
# 使用替换方法而不是format
readme_content = template_content.replace("{hosts_str}", hosts_str)
readme_content = readme_content.replace("{update_time}", update_time)
# 写入新文件
with open("README.md", "w", encoding="utf-8") as output_fb:
output_fb.write(readme_content)
rprint(
"[blue]已更新 README.md 文件,位于: [underline]README.md[/underline][/blue]\n"
)
except FileNotFoundError as e:
print(f"错误: {str(e)}")
except Exception as e:
print(f"生成 README.md 文件时发生错误: {str(e)}")
def get_formatted_line(char="-", color="green", width_percentage=0.97):
"""
生成格式化的分隔线
参数:
char: 要重复的字符
color: rich支持的颜色名称
width_percentage: 终端宽度的百分比(0.0-1.0)
"""
# 获取终端宽度
terminal_width = shutil.get_terminal_size().columns
# 计算目标宽度(终端宽度的指定百分比)
target_width = floor(terminal_width * width_percentage)
# 生成重复字符
line = char * target_width
# 返回带颜色标记的行
return f"[{color}]{line}[/{color}]"
def get_formatted_output(text, fill_char=".", align_position=0.97):
"""
格式化输出文本,确保不超出终端宽度
参数:
text: 要格式化的文本
fill_char: 填充字符
align_position: 终端宽度的百分比(0.0-1.0)
"""
# 获取终端宽度并计算目标宽度
terminal_width = shutil.get_terminal_size().columns
target_width = floor(terminal_width * align_position)
# 移除rich标记计算实际文本长度
plain_text = (
text.replace("[blue on green]", "").replace("[/blue on green]", "")
# .replace("[完成]", "")
)
if "[完成]" in text:
main_text = plain_text.strip()
completion_mark = "[完成]"
# 关键修改:直接从目标宽度减去主文本长度,不再额外预留[完成]的空间
fill_count = target_width - len(main_text) - len(completion_mark) - 6
fill_count = max(0, fill_count)
filled_text = f"{main_text}{fill_char * fill_count}{completion_mark}"
return f"[blue on green]{filled_text}[/blue on green]"
else:
# 普通文本的处理保持不变
fill_count = target_width - len(plain_text.strip()) - 6
fill_count = max(0, fill_count)
filled_text = f"{plain_text.strip()}{' ' * fill_count}"
return f"[blue on green]{filled_text}[/blue on green]"
def get_align_str(
i,
group_name,
reference_str="启动 setHosts 自动更新··· ",
):
"""
创建一个经过填充的进度字符串,使其显示宽度与参考字符串相同
Args:
i: 当前处理的组索引
group_name: 组名称
reference_str: 参考字符串,用于对齐长度
Returns:
调整后的格式化字符串
"""
# 计算参考字符串的显示宽度
ref_width = wcwidth.wcswidth(reference_str)
# 构建基础字符串(不包含尾部填充)
base_str = f"正在处理第 {i} 组域名: {group_name.upper()}"
# 计算基础字符串的显示宽度
base_width = wcwidth.wcswidth(base_str)
# 计算需要添加的空格数量
# 需要考虑Rich标签不计入显示宽度
padding_needed = ref_width - base_width
# 确保填充不会为负数
padding_needed = max(0, padding_needed)
# 构建最终的格式化字符串
formatted_str = f"\n[bold white on bright_black]正在处理第 [green]{i}[/green] 组域名: {group_name.upper()}{' ' * padding_needed}[/bold white on bright_black]"
return formatted_str
# -------------------- 域名与分组管理 -------------------- #
class GroupType(Enum):
SHARED = "shared hosts" # 多个域名共用一组DNS主机 IP
SEPARATE = "separate hosts" # 每个域名独立拥有DNS主机 IP
class DomainGroup:
def __init__(
self,
name: str,
domains: List[str],
ips: Optional[Set[str]] = None,
group_type: GroupType = GroupType.SHARED,
):
self.name = name
self.domains = domains if isinstance(domains, list) else [domains]
self.ips = ips or set()
self.group_type = group_type
# -------------------- 域名解析模块 -------------------- #
class DomainResolver:
# 设置缓存过期时间为1周
DNS_CACHE_EXPIRY_TIME = timedelta(weeks=1)
def __init__(self, dns_servers: List[str], max_latency: int, dns_cache_file: str):
self.dns_servers = dns_servers
self.max_latency = max_latency
self.dns_cache_file = Path(dns_cache_file)
self.dns_records = self._init_dns_cache()
def _init_dns_cache(self) -> dict:
"""初始化 DNS 缓存,如果缓存文件存在且未过期则加载,否则返回空字典"""
if self._is_dns_cache_valid():
return self.load_hosts_cache()
# 如果 DNS 缓存过期,删除旧缓存文件
if self.dns_cache_file.exists():
self.dns_cache_file.unlink()
return {}
def _is_dns_cache_valid(self) -> bool:
"""检查 DNS 缓存是否有效"""
if not self.dns_cache_file.exists():
return False
file_age = datetime.now() - datetime.fromtimestamp(
os.path.getmtime(self.dns_cache_file)
)
return file_age <= self.DNS_CACHE_EXPIRY_TIME
def load_hosts_cache(self) -> Dict[str, Dict]:
try:
with open(self.dns_cache_file, "r", encoding="utf-8") as f:
return json.load(f)
except Exception as e:
logging.error(f"加载 DNS 缓存文件失败: {e}")
return {}
def save_hosts_cache(self):
try:
with open(self.dns_cache_file, "w", encoding="utf-8") as f:
json.dump(self.dns_records, f, indent=4, ensure_ascii=False)
logging.debug(f"成功保存 DNS 缓存到文件 {self.dns_cache_file}")
except Exception as e:
logging.error(f"保存 DNS 缓存到文件时发生错误: {e}")
async def resolve_domain(self, domain: str) -> Set[str]:
start_time = datetime.now()
ips = set()
# 1. 首先通过常规DNS服务器解析
dns_ips = await self._resolve_via_dns(domain, "all")
ips.update(dns_ips)
dns_resolve_end_time = datetime.now()
dns_resolve_duration = dns_resolve_end_time - start_time
logging.debug(f"DNS解析耗时: {dns_resolve_duration.total_seconds():.2f}秒")
# 2. 然后通过DNS_records解析
# 由于init时已经处理了过期文件,这里只需要检查域名是否在缓存中
if domain in self.dns_records:
domain_hosts = self.dns_records.get(domain, {})
ipv4_ips = domain_hosts.get("ipv4", [])
ipv6_ips = domain_hosts.get("ipv6", [])
ips.update(ipv4_ips + ipv6_ips)
logging.debug(
f"成功通过缓存文件解析 {domain}, 发现 {len(ipv4_ips) + len(ipv6_ips)} 个 DNS 主机:\n{ipv4_ips}\n{ipv6_ips if ipv6_ips else ''}\n"
)
else:
ipaddress_ips = await self._resolve_via_ipaddress(domain)
if ipaddress_ips:
ips.update(ipaddress_ips)
if ips:
logging.debug(
f"成功通过 DNS服务器 和 DNS记录 解析 {domain}, 发现 {len(ips)} 个 唯一 DNS 主机\n{ips}\n"
)
else:
logging.debug(f"警告: 无法解析 {domain}")
ipaddress_resolve_end_time = datetime.now()
ipaddress_resolve_duration = ipaddress_resolve_end_time - dns_resolve_end_time
total_resolve_duration = ipaddress_resolve_end_time - start_time
logging.debug(
f"IP地址解析耗时: {ipaddress_resolve_duration.total_seconds():.2f}秒"
)
logging.debug(f"DNS解析总耗时: {total_resolve_duration.total_seconds():.2f}秒")
return ips
async def _resolve_via_dns(self, domain: str, dns_type: str = "all") -> Set[str]:
"""
通过 DNS 解析域名
:param domain: 待解析的域名
:param dns_type: 解析使用的 DNS 类型。可选值:
- "all": 同时使用国内和国际 DNS
- "china": 仅使用国内 DNS
- "international": 仅使用国际 DNS
:return: 解析得到的 IP 集合
"""
async def resolve_with_dns_server(dns_server_info: dict) -> Set[str]:
"""单个DNS服务器的解析协程"""
dns_server = dns_server_info["ip"]
dns_provider = dns_server_info["provider"]
ips = set()
resolver = dns.resolver.Resolver(configure=False)
resolver.nameservers = [dns_server]
resolver.timeout = RESOLVER_TIMEOUT
resolver.lifetime = RESOLVER_TIMEOUT
try:
# 使用 to_thread 在线程池中执行同步的 DNS 查询
for qtype in ["A", "AAAA"]:
try:
answers = await asyncio.to_thread(
resolver.resolve, domain, qtype
)
ips.update(answer.address for answer in answers)
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN):
pass
except Exception as e:
logging.debug(f"DNS 查询异常 ({qtype}, {dns_server}): {e}")
if ips:
logging.debug(
f"成功使用 {dns_provider} : {dns_server} 解析 {domain},共 {len(ips)} 个主机: {ips}"
)
return ips
except Exception as e:
logging.debug(f"使用 {dns_server} 解析 {domain} 失败: {e}")
return set()
# 根据 dns_type 选择要使用的 DNS 服务器
if dns_type.lower() == "all":
dns_servers = (
self.dns_servers["china_mainland"] + self.dns_servers["international"]
)
elif dns_type.lower() == "china":
dns_servers = self.dns_servers["china_mainland"]
elif dns_type.lower() == "global" or dns_type.lower() == "international":
dns_servers = self.dns_servers["international"]
else:
dns_servers = (
self.dns_servers["china_mainland"] + self.dns_servers["international"]
)
# raise ValueError(f"无效的 DNS 类型:{dns_type}")
# 并发解析所有选定的 DNS 服务器,并保留非空结果
tasks = [resolve_with_dns_server(dns_server) for dns_server in dns_servers]
results = await asyncio.gather(*tasks)
# 合并所有非空的解析结果
ips = set(ip for result in results for ip in result if ip)
if ips:
logging.debug(
f"成功使用多个 DNS 服务器解析 {domain},共 {len(ips)} 个主机:\n{ips}\n"
)
# input("按任意键继续")
return ips
def retry_async(tries=3, delay=0):
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
domain = args[1]
for attempt in range(tries):
try:
return await func(*args, **kwargs)
except Exception:
if attempt < tries - 1:
print(f"第 {attempt + 2} 次尝试:")
# logging.debug(f"通过DNS_records解析 {args[1]},第 {attempt + 2} 次尝试:")
if attempt == tries - 1:
self = args[0] # 明确 self 的引用
domain = args[1]
current_time = datetime.now().isoformat()
self.dns_records[domain] = {
"last_update": current_time,
"ipv4": [],
"ipv6": [],
"source": "DNS_records",
}
self.save_hosts_cache()
logging.warning(
f"ipaddress.com {tries} 次尝试后未解析到 {domain} 的 DNS_records 地址,"
f"已写入空地址到缓存以免无谓消耗网络资源"
)
# print(f"通过 DNS_records 解析 {
# domain},{tries} 次尝试后终止!")
return None
await asyncio.sleep(delay)
return None
return wrapper
return decorator
LOGGING_CONFIG = {
"version": 1,
"handlers": {
"httpxHandlers": {
"class": "logging.StreamHandler",
"formatter": "http",
"stream": "ext://sys.stderr",
}
},
"formatters": {
"http": {
"format": "%(levelname)s [%(asctime)s] %(name)s - %(message)s",
"datefmt": "%Y-%m-%d %H:%M:%S",
}
},
"loggers": {
"httpx": {
"handlers": ["httpxHandlers"],
"level": "WARNING",
},
"httpcore": {
"handlers": ["httpxHandlers"],
"level": "WARNING",
},
},
}
logging.config.dictConfig(LOGGING_CONFIG)
@retry_async(tries=3)
async def _resolve_via_ipaddress(self, domain: str) -> Set[str]:
ips = set()
url = f"https://www.ipaddress.com/website/{domain}"
# headers = {
# "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
# "AppleWebKit/537.36 (KHTML, like Gecko) "
# "Chrome/106.0.0.0 Safari/537.36"
# }
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.5615.121 Safari/537.36",
"Referer": "https://www.ipaddress.com",
}
try:
async with httpx.AsyncClient(
timeout=httpx.Timeout(1.0),
follow_redirects=True,
http2=True,
) as client:
response = await client.get(url, headers=headers)
# # 使用内置方法检查状态码
response.raise_for_status() # 自动处理非200状态码
content = response.text
ipv4_pattern = r">((?:[0-9]{1,3}\.){3}[0-9]{1,3})\b<"
# ipv6_pattern = r">((?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4})<"
# 支持ipv6压缩
ipv6_pattern = r">((?:[0-9a-fA-F]{1,4}:){2,7}[0-9a-fA-F]{1,4}|[0-9a-fA-F]{1,4}(?::[0-9a-fA-F]{1,4}){0,5}::[0-9a-fA-F]{1,6})<"
ipv4_ips = set(re.findall(ipv4_pattern, content))
ipv6_ips = set(re.findall(ipv6_pattern, content))
ips.update(ipv4_ips)
ips.update(ipv6_ips)
if ips:
current_time = datetime.now().isoformat()
self.dns_records[domain] = {
"last_update": current_time,
"ipv4": list(ipv4_ips),
"ipv6": list(ipv6_ips),
"source": "DNS_records",
}
self.save_hosts_cache()
logging.debug(
f"通过 ipaddress.com 成功解析 {domain} 并更新 DNS_records 缓存"
)
logging.debug(f"DNS_records:\n {ips}")
else:
self.dns_records[domain] = {
"last_update": datetime.now().isoformat(),
"ipv4": [],
"ipv6": [],
"source": "DNS_records",
}
self.save_hosts_cache()
logging.warning(
f"ipaddress.com 未解析到 {domain} 的 DNS_records 地址,已写入空地址到缓存以免无谓消耗网络资源"
)
except Exception as e:
logging.error(f"通过DNS_records解析 {domain} 失败! {e}")
raise
return ips
# -------------------- 延迟测速模块 -------------------- #
class LatencyTester:
def __init__(self, hosts_num: int, max_workers: int = 200):
self.hosts_num = hosts_num
self.max_workers = max_workers
async def get_lowest_latency_hosts(
self,
group_name: str,
domains: List[str],
file_ips: Set[str],
latency_limit: int,
) -> List[Tuple[str, float]]:
"""
使用线程池和异步操作优化IP延迟和SSL证书验证
"""
all_ips = list(file_ips)
# start_time = datetime.now()
rprint(
f"[bright_black]- 获取到 [bold bright_green]{len(all_ips)}[/bold bright_green] 个唯一IP地址[/bright_black]"
)
if all_ips:
rprint("[bright_black]- 检测主机延迟...[/bright_black]")
# 使用线程池来并发处理SSL证书验证
with concurrent.futures.ThreadPoolExecutor(
max_workers=self.max_workers
) as executor:
# 第一步:并发获取IP延迟
ping_tasks = [self.get_host_average_latency(ip) for ip in all_ips]
latency_results = await asyncio.gather(*ping_tasks)
# 筛选有效延迟的IP
valid_latency_results = [
result for result in latency_results if result[1] != float("inf")
]
if valid_latency_results:
if len(valid_latency_results) < len(all_ips):
rprint(
f"[bright_black]- 检测到 [bold bright_green]{len(valid_latency_results)}[/bold bright_green] 个有效IP地址[/bright_black]"
)
valid_latency_ips = [
result
for result in valid_latency_results
if result[1] < latency_limit
]
if not valid_latency_ips:
logging.warning(f"未发现延迟小于 {latency_limit}ms 的IP。")
min_result = [min(valid_latency_results, key=lambda x: x[1])]
latency_limit = min_result[0][1] * 2
logging.debug(f"主机IP最低延迟 {latency_limit:.0f}ms")
valid_latency_ips = [
result
for result in valid_latency_results
if result[1] <= latency_limit
]
else:
rprint("[red]延迟检测没有获得有效IP[/red]")
return []
# 排序结果
valid_latency_ips = sorted(valid_latency_ips, key=lambda x: x[1])
if len(valid_latency_ips) < len(valid_latency_results):
rprint(
f"[bright_black]- 检测到 [bold bright_green]{len(valid_latency_ips)}[/bold bright_green] 个延迟小于 {latency_limit}ms 的有效IP地址[/bright_black]"
)
ipv4_results = [r for r in valid_latency_ips if not Utils.is_ipv6(r[0])]
ipv6_results = [r for r in valid_latency_ips if Utils.is_ipv6(r[0])]
# 第二步:使用线程池并发验证SSL证书
# if "github" in group_name.lower():
if len(valid_latency_ips) > 1 and any(
keyword in group_name.lower() for keyword in ["google"]
):
rprint("[bright_black]- 验证SSL证书...[/bright_black]")
ipv4_count = 0
ipv6_count = 0
batch_size = args.batch_size
total_results = len(valid_latency_ips)
valid_results = []
loop = asyncio.get_running_loop()
for i in range(0, total_results, batch_size):
min_len = min(total_results, batch_size)
batch = valid_latency_ips[i : i + min_len]
ssl_verification_tasks = [
loop.run_in_executor(
executor,
self._sync_is_cert_valid_dict,
domains[0],
ip,
latency,
)
for ip, latency in batch
]
for future in asyncio.as_completed(ssl_verification_tasks):
ip, latency, ssl_valid = await future
if ssl_valid:
valid_results.append((ip, latency))
if Utils.is_ipv6(ip):
ipv6_count += 1
else:
ipv4_count += 1
if ipv6_results:
if ipv4_results:
if ipv6_count >= 1 and ipv4_count >= 1:
break
else:
if ipv6_count >= 1:
break
else:
if ipv4_count >= self.hosts_num:
break
if ipv6_results:
if ipv4_results:
if ipv6_count >= 1 and ipv4_count >= 1:
break
else:
if ipv6_count >= 1:
break
else:
if ipv4_count >= self.hosts_num:
break
else:
valid_results = valid_latency_ips
# 按延迟排序并选择最佳主机
valid_results = sorted(valid_results, key=lambda x: x[1])
if not valid_results:
rprint(f"[red]未发现延迟小于 {latency_limit}ms 且证书有效的IP。[/red]")
# 选择最佳主机(支持IPv4和IPv6)
best_hosts = self._select_best_hosts(valid_results)
# 打印结果(可以根据需要保留或修改原有的打印逻辑)
self._print_results(best_hosts, latency_limit)
return best_hosts
async def get_host_average_latency(
self, ip: str, port: int = 443
) -> Tuple[str, float]:
try:
response_times = await asyncio.gather(
*[self.get_latency(ip, port) for _ in range(NUM_PINGS)]
)
response_times = [t for t in response_times if t != float("inf")]
if response_times:
average_response_time = sum(response_times) / len(response_times)
else:
average_response_time = float("inf")
if average_response_time == 0:
logging.error(f"{ip} 平均延迟为 0 ms,视为无效")
return ip, float("inf")
logging.debug(f"{ip} 平均延迟: {average_response_time:.2f} ms")
return ip, average_response_time
except Exception as e:
logging.debug(f"ping {ip} 时出错: {e}")
return ip, float("inf")
async def get_latency(self, ip: str, port: int = 443) -> float:
try:
# 使用 getaddrinfo 来获取正确的地址格式
addrinfo = await asyncio.get_event_loop().getaddrinfo(
ip, port, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM
)
for family, type, proto, canonname, sockaddr in addrinfo:
try:
start = asyncio.get_event_loop().time()
_, writer = await asyncio.wait_for(
asyncio.open_connection(sockaddr[0], sockaddr[1]),
timeout=PING_TIMEOUT,
)
end = asyncio.get_event_loop().time()
writer.close()
await writer.wait_closed()
return (end - start) * 1000
except asyncio.TimeoutError:
continue
except Exception as e:
logging.debug(f"连接测试失败 {ip} (sockaddr: {sockaddr}): {e}")
continue
return float("inf")
except Exception as e:
logging.error(f"获取地址信息失败 {ip}: {e}")
return float("inf")
def _sync_is_cert_valid_dict(
self, domain: str, ip: str, latency: float, port: int = 443
) -> Tuple[str, float, bool]:
"""
同步版本的证书验证方法,用于在线程池中执行
"""
try:
context = ssl.create_default_context()
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
with socket.create_connection((ip, port), timeout=2) as sock:
with context.wrap_socket(sock, server_hostname=domain) as ssock:
cert = ssock.getpeercert()
not_after = datetime.strptime(
cert["notAfter"], "%b %d %H:%M:%S %Y %Z"
)
if not_after < datetime.now():
logging.debug(f"{domain} ({ip}) {latency:.0f}ms: 证书已过期")
return (ip, latency, False)
logging.debug(
f"{domain} ({ip}) {latency:.0f}ms: SSL证书有效,截止日期为 {not_after}"
)
return (ip, latency, True)
except ConnectionError as e:
logging.debug(
f"{domain} ({ip}) {latency:.0f}ms: 连接被强迫关闭,ip有效 - {e}"
)
return (ip, latency, True)
except Exception as e:
logging.debug(f"{domain} ({ip}) {latency:.0f}ms: 证书验证失败 - {e}")
return (ip, latency, False)
def _sync_is_cert_valid_dict_average(
self, domains: List[str], ip: str, latency: float, port: int = 443
) -> Tuple[str, float, bool]:
"""
同步版本的证书验证方法,用于在线程池中执行。
任意一个 domain 验证通过就视为通过。
"""
for domain in domains:
try:
context = ssl.create_default_context()
context.verify_mode = ssl.CERT_REQUIRED
context.check_hostname = True
with socket.create_connection((ip, port), timeout=2) as sock:
with context.wrap_socket(sock, server_hostname=domain) as ssock:
cert = ssock.getpeercert()
not_after = datetime.strptime(
cert["notAfter"], "%b %d %H:%M:%S %Y %Z"
)
if not_after < datetime.now():
logging.debug(
f"{domain} ({ip}) {latency:.0f}ms: 证书已过期"
)
continue # 检查下一个 domain
logging.debug(
f"{domain} ({ip}) {latency:.0f}ms: SSL证书有效,截止日期为 {not_after}"
)
return (ip, latency, True) # 任意一个验证通过即返回成功
except ConnectionError as e:
logging.debug(
f"{domain} ({ip}) {latency:.0f}ms: 连接被强迫关闭,ip有效 - {e}"
)
return (ip, latency, True)
except Exception as e:
logging.debug(f"{domain} ({ip}) {latency:.0f}ms: 证书验证失败 - {e}")
continue # 检查下一个 domain
# 如果所有 domain 都验证失败
return (ip, latency, False)
def _select_best_hosts(
self, valid_results: List[Tuple[str, float]]
) -> List[Tuple[str, float]]:
"""
选择最佳主机,优先考虑IPv4和IPv6
"""
ipv4_results = [r for r in valid_results if not Utils.is_ipv6(r[0])]
ipv6_results = [r for r in valid_results if Utils.is_ipv6(r[0])]
best_hosts = []
selected_count = 0
if ipv4_results:
min_ipv4_results = min(ipv4_results, key=lambda x: x[1])
# 先选择IPv4
if ipv4_results:
logging.debug(f"有效IPv4:\n{ipv4_results}\n")
for ip, latency in ipv4_results:
best_hosts.append((ip, latency))
selected_count += 1
if (
ipv6_results and selected_count >= 1
) or selected_count >= self.hosts_num:
break
# 再选择IPv6
if ipv6_results:
logging.debug(f"有效IPv6:\n{ipv6_results}\n")
for ip, latency in ipv6_results:
if ipv4_results and latency <= min_ipv4_results[1] * 2:
best_hosts.append((ip, latency))
break
else:
best_hosts.append((ip, latency))
break
return best_hosts
def _print_results(self, best_hosts: List[Tuple[str, float]], latency_limit: int):
"""
打印结果的方法
"""
rprint(
f"[bold yellow]最快的 DNS主机 IP(优先选择 IPv6) 丨 延迟 < {latency_limit:.0f}ms :[/bold yellow]"
)
for ip, time in best_hosts:
rprint(
f" [green]{ip}[/green] [bright_black]{time:.2f} ms[/bright_black]"
)
# end_time = datetime.now()
# total_time = end_time - start_time
# rprint(
# f"[bright_black]- 运行时间:[/bright_black] [cyan]{total_time.total_seconds():.2f} 秒[/cyan]")
# -------------------- Hosts文件管理 -------------------- #
class HostsManager:
def __init__(self):
# 自动根据操作系统获取hosts文件路径
self.hosts_file_path = self._get_hosts_file_path()
@staticmethod
def _get_hosts_file_path() -> str:
"""根据操作系统自动获取 hosts 文件路径。"""
return Utils.get_hosts_file_path()
def write_to_hosts_file(self, new_entries: List[str]):
Utils.backup_hosts_file(self.hosts_file_path)
with open(self.hosts_file_path, "r") as f:
existing_content = f.read().splitlines()
new_domains = {
entry.split()[1] for entry in new_entries if len(entry.split()) >= 2
}
new_content = []
skip = False
skip_tags = ("# cnNetTool", "# Update", "# Star", "# GitHub")
for line in existing_content:
line = line.strip()
# 跳过标记块
if any(line.startswith(tag) for tag in skip_tags):
skip = True
if line == "":
skip = True
if skip:
if line == "" or line.startswith("#"):
continue
skip = False
# 非标记块内容保留
if (
not skip
and (line.startswith("#") or not line)
and not any(tag in line for tag in skip_tags)
):
new_content.append(line)
continue
# 检查域名是否为新条目
parts = line.split()
if len(parts) >= 2 and parts[1] not in new_domains:
new_content.append(line)
else:
logging.debug(f"删除旧条目: {line}")
update_time = (
datetime.now(timezone.utc)
.astimezone(timezone(timedelta(hours=8)))
.strftime("%Y-%m-%d %H:%M:%S %z")
.replace("+0800", "+08:00")
)
rprint("\n[bold yellow]正在更新 hosts 文件...[/bold yellow]")
save_hosts_content = [] # 提取新内容文本
# 1. 添加标题
new_content.append(f"\n# cnNetTool Start in {update_time}")
save_hosts_content.append(f"\n# cnNetTool Start in {update_time}")
# 2. 添加主机条目
for entry in new_entries:
# 分割 IP 和域名
ip, domain = entry.strip().split(maxsplit=1)
# 计算需要的制表符数量
# IP 地址最长可能是 39 个字符 (IPv6)
# 我们使用制表符(8个空格)来对齐,确保视觉上的整齐
ip_length = len(ip)
if ip_length <= 8: