-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrpc.py
More file actions
1717 lines (1478 loc) · 67.5 KB
/
frpc.py
File metadata and controls
1717 lines (1478 loc) · 67.5 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
import os, sys, re, json, tomllib, yaml, shutil, zipfile, tarfile, platform, subprocess, tempfile, threading, traceback, logging, asyncio, aiofiles, hashlib, urllib.request
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple
from urllib.request import urlretrieve
from urllib.error import URLError
from datetime import datetime
from pathlib import Path
# ======================== 基础配置 ========================
# 支持的配置文件类型
SUPPORTED_CONFIG_TYPES = ['.ini', '.yml', '.yaml', '.toml', '.json']
# FRPC版本和下载地址
FRPC_VERSION = "0.67.0"
FRPC_DOWNLOAD_URLS = {
"windows_amd64": f"https://github.com/fatedier/frp/releases/download/v{FRPC_VERSION}/frp_{FRPC_VERSION}_windows_amd64.zip",
"linux_amd64": f"https://github.com/fatedier/frp/releases/download/v{FRPC_VERSION}/frp_{FRPC_VERSION}_linux_amd64.tar.gz",
"darwin_amd64": f"https://github.com/fatedier/frp/releases/download/v{FRPC_VERSION}/frp_{FRPC_VERSION}_darwin_amd64.tar.gz",
"darwin_arm64": f"https://github.com/fatedier/frp/releases/download/v{FRPC_VERSION}/frp_{FRPC_VERSION}_darwin_arm64.tar.gz"
}
# 配置模板
CONFIG_TEMPLATES = {
"默认TCP代理": """[common]
server_addr = {server_ip}
server_port = {server_port}
token = {token}
[ssh]
type = tcp
local_ip = 127.0.0.1
local_port = 22
remote_port = {remote_port}
""",
"HTTP反向代理": """[common]
server_addr = {server_ip}
server_port = {server_port}
token = {token}
[web]
type = http
local_ip = 127.0.0.1
local_port = 80
custom_domains = {domain}
""",
"UDP代理(游戏)": """[common]
server_addr = {server_ip}
server_port = {server_port}
token = {token}
[game]
type = udp
local_ip = 127.0.0.1
local_port = {local_port}
remote_port = {remote_port}
"""
}
# INI语法高亮规则
SYNTAX_RULES = {
'section': re.compile(r'\[.*?\]'),
'key': re.compile(r'(\w+)\s*='),
'comment': re.compile(r'#.*'),
'string': re.compile(r'"[^"]*"|\'[^\']*\''),
'number': re.compile(r'\b\d+\b')
}
# 错误分析规则
ERROR_ANALYSIS_RULES = [
{
'pattern': r'lookup (.+) on (.+):53: no such host',
'type': 'DNS解析失败',
'description': '域名解析失败,无法找到指定的frp服务器域名',
'solutions': [
'检查frp服务器域名是否正确',
'确认本地DNS配置是否正常',
'尝试使用服务器IP地址代替域名',
'检查网络连接和DNS服务器可用性'
]
},
{
'pattern': r'dial tcp (.+): connect: connection refused',
'type': '连接被拒绝',
'description': '无法连接到frp服务器指定端口,服务器可能未启动或端口未开放',
'solutions': [
'检查frp服务器是否正常运行',
'确认server_port配置是否正确',
'检查服务器防火墙/安全组是否开放该端口',
'验证服务器IP地址是否正确'
]
},
{
'pattern': r'no route to host',
'type': '无路由到主机',
'description': '网络不通,无法访问frp服务器',
'solutions': [
'检查本地网络连接',
'验证服务器IP地址是否可达 (ping测试)',
'检查防火墙/路由器设置',
'确认服务器是否在线'
]
},
{
'pattern': r'authentication failed',
'type': '认证失败',
'description': 'token验证失败,客户端与服务器token不匹配',
'solutions': [
'检查common配置中的token是否正确',
'确认frp服务器端的token配置',
'token区分大小写,请检查拼写'
]
},
{
'pattern': r'address already in use',
'type': '端口被占用',
'description': '本地端口已被其他程序占用',
'solutions': [
'更换local_port为未被占用的端口',
'查找并关闭占用该端口的程序',
'使用netstat -ano (Windows) 或 lsof -i:端口号 (Linux) 查看端口占用'
]
},
{
'pattern': r'remote port (.+) is already used',
'type': '远程端口已被占用',
'description': '指定的远程端口已被服务器上其他服务占用',
'solutions': [
'更换remote_port为其他未被占用的端口',
'联系frp服务器管理员确认端口使用情况',
'检查端口是否在服务器防火墙/安全组中开放'
]
},
{
'pattern': r'permission denied',
'type': '权限不足',
'description': '没有足够的权限绑定端口或运行程序',
'solutions': [
'使用管理员/root权限运行frpc',
'避免使用1024以下的特权端口',
'检查文件/目录访问权限'
]
},
{
'pattern': r'context deadline exceeded',
'type': '连接超时',
'description': '连接frp服务器超时',
'solutions': [
'检查网络延迟和稳定性',
'增加连接超时时间配置',
'确认服务器是否在公网可访问',
'检查MTU设置是否合适'
]
}
]
# ======================== 增强的验证规则 ========================
VALIDATION_RULES = {
'server_addr': {
'pattern': r'^(\d{1,3}\.){3}\d{1,3}$|^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$',
'error': '无效的IP地址或域名格式',
'required': True
},
'server_port': {
'range': (1, 65535),
'error': '端口必须在1-65535之间',
'required': True
},
'token': {
'min_length': 1,
'error': 'token不能为空(如果服务器配置了认证)',
'required': False
},
'local_port': {
'range': (1, 65535),
'error': '本地端口必须在1-65535之间',
'required': True
},
'remote_port': {
'range': (1, 65535),
'error': '远程端口必须在1-65535之间',
'required': True
},
'local_ip': {
'pattern': r'^(\d{1,3}\.){3}\d{1,3}$|^localhost$',
'error': '无效的本地IP地址格式',
'required': True,
'default': '127.0.0.1'
}
}
# ======================== YAML Schema 验证 ========================
FRPC_SCHEMA = {
'type': 'object',
'required': ['common'],
'properties': {
'common': {
'type': 'object',
'required': ['server_addr', 'server_port'],
'properties': {
'server_addr': {'type': 'string'},
'server_port': {'type': 'integer', 'minimum': 1, 'maximum': 65535},
'token': {'type': 'string'},
'protocol': {'type': 'string', 'enum': ['tcp', 'kcp', 'websocket']},
'log_level': {'type': 'string', 'enum': ['trace', 'debug', 'info', 'warn', 'error']}
}
}
}
}
# ======================== 日志配置 ========================
def setup_logging():
"""配置结构化日志"""
# 创建日志目录
log_dir = Path("frpc_manager_logs")
log_dir.mkdir(exist_ok=True)
# 配置日志格式
log_format = '%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s'
# 文件处理器
log_file = log_dir / f"frpc_manager_{datetime.now().strftime('%Y%m%d')}.log"
file_handler = logging.FileHandler(log_file, encoding='utf-8')
file_handler.setFormatter(logging.Formatter(log_format))
file_handler.setLevel(logging.DEBUG)
# 控制台处理器
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(log_format))
console_handler.setLevel(logging.INFO)
# 配置根日志器
logger = logging.getLogger('frpc_manager')
logger.setLevel(logging.DEBUG)
logger.addHandler(file_handler)
logger.addHandler(console_handler)
return logger
# 初始化日志
logger = setup_logging()
# ======================== 数据类 ========================
@dataclass
class FRPCConfig:
"""FRPC 配置数据类"""
server_ip: str
server_port: int
token: str
proxies: List[Dict[str, str]]
extra_common: str = ""
@dataclass
class FRPCRuntimeInfo:
"""FRPC 运行时信息"""
process: Optional[subprocess.Popen] = None
restart_count: int = 0
max_restarts: int = 3
restart_delay: int = 5 # 重启延迟秒数
stop_flag: bool = False
log_buffer: List[str] = field(default_factory=list)
last_error: str = ""
@dataclass
class ConfigVersion:
"""配置文件版本信息"""
file_path: str
version: str
timestamp: datetime
hash: str
backup_path: str = ""
# ======================== 终端颜色类 ========================
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
# ======================== 工具函数 ========================
def clear_screen():
"""清屏函数"""
os.system('cls' if platform.system() == 'Windows' else 'clear')
def supports_color():
"""检查终端是否支持颜色"""
return not platform.system() == 'Windows' or 'ANSICON' in os.environ
def calculate_file_hash(file_path: str) -> str:
"""计算文件的MD5哈希值"""
try:
hash_md5 = hashlib.md5()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
except Exception as e:
logger.error(f"计算文件哈希失败: {e}")
return ""
def show_progress(block_num: int, block_size: int, total_size: int):
"""下载进度显示"""
if total_size <= 0:
return
progress = min(block_num * block_size / total_size * 100, 100)
print(f"\r下载进度: {progress:.1f}%", end='', flush=True)
def backup_config(file_path: str) -> str:
"""备份配置文件"""
try:
# 修复:使用Path对象处理路径
backup_dir = Path("frpc_backups")
backup_dir.mkdir(exist_ok=True)
timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
backup_file = backup_dir / f"{Path(file_path).name}.{timestamp}.bak"
# 复制文件
shutil.copy2(file_path, backup_file)
# 记录版本信息
version_info = ConfigVersion(
file_path=file_path,
version=timestamp,
timestamp=datetime.now(),
hash=calculate_file_hash(file_path),
backup_path=str(backup_file)
)
# 保存版本信息 - 修复:datetime序列化问题
version_file = Path(f"{file_path}.versions.json")
versions = []
if version_file.exists():
with open(version_file, 'r', encoding='utf-8') as f:
versions = json.load(f)
versions.append({
'file_path': version_info.file_path,
'version': version_info.version,
'timestamp': version_info.timestamp.isoformat(), # 修复:使用ISO格式序列化时间
'hash': version_info.hash,
'backup_path': version_info.backup_path
})
with open(version_file, 'w', encoding='utf-8') as f:
json.dump(versions, f, ensure_ascii=False, indent=2)
logger.info(f"配置文件已备份: {backup_file}")
return str(backup_file)
except Exception as e:
logger.error(f"备份配置文件失败: {e}")
return ""
def rollback_config(file_path: str) -> bool:
"""回滚配置文件到上一个版本"""
try:
version_file = Path(f"{file_path}.versions.json")
if not version_file.exists():
logger.warning("没有版本记录,无法回滚")
print(f"{bcolors.WARNING}没有版本记录,无法回滚{bcolors.ENDC}")
return False
with open(version_file, 'r', encoding='utf-8') as f:
versions = json.load(f)
if len(versions) < 1:
logger.warning("没有备份版本,无法回滚")
print(f"{bcolors.WARNING}没有备份版本,无法回滚{bcolors.ENDC}")
return False
# 获取最新备份
latest_version = versions[-1]
backup_path = latest_version['backup_path']
if not Path(backup_path).exists():
logger.error(f"备份文件不存在: {backup_path}")
print(f"{bcolors.FAIL}备份文件不存在{bcolors.ENDC}")
return False
# 先备份当前版本
backup_config(file_path)
# 恢复备份
shutil.copy2(backup_path, file_path)
logger.info(f"配置文件已回滚到版本 {latest_version['version']}")
print(f"{bcolors.OKGREEN}配置文件已回滚到版本 {latest_version['version']}{bcolors.ENDC}")
return True
except Exception as e:
logger.error(f"回滚配置失败: {e}")
print(f"{bcolors.FAIL}回滚失败: {e}{bcolors.ENDC}")
return False
def check_file_permissions(file_path: str) -> bool:
"""检查配置文件权限是否安全"""
try:
file_path = Path(file_path)
if platform.system() == 'Windows':
# Windows权限检查(简化版)
return True
else:
# Linux/macOS权限检查
stat = file_path.stat()
# 检查是否只有所有者可写
if (stat.st_mode & 0o022) != 0:
logger.warning(f"配置文件权限不安全: {file_path} (其他用户可写)")
print(f"{bcolors.WARNING}警告: 配置文件 {file_path} 权限不安全,建议执行: chmod 600 {file_path}{bcolors.ENDC}")
return False
return True
except Exception as e:
logger.error(f"检查文件权限失败: {e}")
return True
# ======================== 核心功能实现 ========================
def syntax_highlight_ini(content: str) -> str:
"""INI 语法高亮"""
if not supports_color():
return content
lines = content.split('\n')
highlighted = []
for line in lines:
line = SYNTAX_RULES['comment'].sub(f"{bcolors.WARNING}\\g<0>{bcolors.ENDC}", line)
line = SYNTAX_RULES['section'].sub(f"{bcolors.HEADER}{bcolors.BOLD}\\g<0>{bcolors.ENDC}", line)
line = SYNTAX_RULES['key'].sub(f"{bcolors.OKBLUE}\\g<1>{bcolors.ENDC} =", line)
line = SYNTAX_RULES['string'].sub(f"{bcolors.OKGREEN}\\g<0>{bcolors.ENDC}", line)
line = SYNTAX_RULES['number'].sub(f"{bcolors.OKCYAN}\\g<0>{bcolors.ENDC}", line)
highlighted.append(line)
return '\n'.join(highlighted)
def validate_field(value: str, rules: Dict) -> Tuple[bool, str]:
"""验证单个字段"""
# 检查是否为空(必填字段)
if rules.get('required', False) and not value:
return False, f"字段不能为空: {rules.get('error', '必填字段')}"
# 如果值为空且非必填,直接通过
if not value and not rules.get('required', False):
return True, ""
# 正则表达式验证
if 'pattern' in rules:
pattern = re.compile(rules['pattern'])
if not pattern.match(value):
return False, rules['error']
# 范围验证(数字)
if 'range' in rules:
try:
num_value = int(value)
min_val, max_val = rules['range']
if not (min_val <= num_value <= max_val):
return False, rules['error']
except ValueError:
return False, "值必须是数字"
# 最小长度验证
if 'min_length' in rules:
if len(value) < rules['min_length']:
return False, rules['error']
return True, ""
def validate_frpc_config(content: str, file_type: str = '.ini') -> Tuple[bool, List[str]]:
"""增强的配置验证"""
errors = []
warnings = []
logger.debug(f"开始验证配置,类型: {file_type}")
try:
if file_type == '.ini':
lines = content.split('\n')
has_common = False
common_section = False
proxy_sections = []
for idx, line in enumerate(lines, 1):
original_line = line
line = line.strip()
if not line or line.startswith('#'):
continue
# 检查段落
if line.startswith('[') and line.endswith(']'):
section = line[1:-1].strip()
if section == 'common':
has_common = True
common_section = True
continue
else:
common_section = False
proxy_sections.append(section)
continue
# 检查键值对
if '=' not in line:
errors.append(f"第{idx}行: 无效的配置格式,缺少 '=' -> {original_line}")
continue
key, value = line.split('=', 1)
key = key.strip()
value = value.strip()
# 字段级验证
if key in VALIDATION_RULES:
is_valid, error_msg = validate_field(value, VALIDATION_RULES[key])
if not is_valid:
errors.append(f"第{idx}行: {key} - {error_msg} -> {original_line}")
# Common 部分验证
if common_section:
if key == 'server_addr' and not value:
errors.append(f"第{idx}行: server_addr (服务器IP) 不能为空 -> {original_line}")
elif key == 'server_port':
try:
port = int(value)
if port < 1 or port > 65535:
warnings.append(f"第{idx}行: server_port {value} 超出有效端口范围(1-65535) -> {original_line}")
except ValueError:
errors.append(f"第{idx}行: server_port {value} 不是有效的数字 -> {original_line}")
if not has_common:
errors.append("缺少 [common] 核心配置段")
if not proxy_sections:
warnings.append("配置文件中未定义任何代理规则")
elif file_type in ['.yml', '.yaml']:
# YAML验证 + Schema检查
data = yaml.safe_load(content)
# 基础Schema验证
if 'common' not in data:
errors.append("缺少 common 配置节点")
else:
common = data['common']
# 验证必填字段
for field in ['server_addr', 'server_port']:
if field not in common:
errors.append(f"common 节点缺少 {field} 字段")
else:
if field in VALIDATION_RULES:
is_valid, error_msg = validate_field(str(common[field]), VALIDATION_RULES[field])
if not is_valid:
errors.append(f"common.{field}: {error_msg}")
elif file_type == '.toml':
data = tomllib.loads(content)
# TOML验证逻辑
if 'common' not in data:
errors.append("缺少 common 配置节点")
else:
common = data['common']
# 验证必填字段
for field in ['server_addr', 'server_port']:
if field not in common:
errors.append(f"common 节点缺少 {field} 字段")
else:
if field in VALIDATION_RULES:
is_valid, error_msg = validate_field(str(common[field]), VALIDATION_RULES[field])
if not is_valid:
errors.append(f"common.{field}: {error_msg}")
elif file_type == '.json':
data = json.loads(content)
# JSON验证逻辑
if 'common' not in data:
errors.append("缺少 common 配置节点")
else:
common = data['common']
# 验证必填字段
for field in ['server_addr', 'server_port']:
if field not in common:
errors.append(f"common 节点缺少 {field} 字段")
else:
if field in VALIDATION_RULES:
is_valid, error_msg = validate_field(str(common[field]), VALIDATION_RULES[field])
if not is_valid:
errors.append(f"common.{field}: {error_msg}")
except yaml.YAMLError as e:
errors.append(f"YAML 语法错误: {str(e)}")
logger.error(f"YAML验证失败: {e}")
except tomllib.TOMLDecodeError as e:
errors.append(f"TOML 语法错误: {str(e)}")
logger.error(f"TOML验证失败: {e}")
except json.JSONDecodeError as e:
errors.append(f"JSON 语法错误: {str(e)}")
logger.error(f"JSON验证失败: {e}")
except Exception as e:
errors.append(f"配置验证失败: {str(e)}")
logger.error(f"配置验证异常: {e}", exc_info=True)
# 整理验证结果
all_messages = []
if errors:
all_messages.extend([f"错误: {e}" for e in errors])
logger.warning(f"配置验证发现 {len(errors)} 个错误")
if warnings:
all_messages.extend([f"警告: {w}" for w in warnings])
logger.info(f"配置验证发现 {len(warnings)} 个警告")
return len(errors) == 0, all_messages
def analyze_frpc_error(log_content: str) -> Dict:
"""分析 frpc 错误日志"""
analysis_result = {
'error_type': '未知错误',
'description': '无法识别的错误类型',
'solutions': ['查看日志详情排查问题'],
'matched_text': '',
'confidence': 0.0
}
if not log_content:
return analysis_result
# 遍历错误分析规则
for rule in ERROR_ANALYSIS_RULES:
pattern = re.compile(rule['pattern'], re.IGNORECASE)
match = pattern.search(log_content)
if match:
analysis_result = {
'error_type': rule['type'],
'description': rule['description'],
'solutions': rule['solutions'],
'matched_text': match.group(0),
'confidence': 1.0
}
logger.debug(f"识别到错误类型: {rule['type']}, 匹配文本: {match.group(0)}")
break
return analysis_result
async def async_monitor_frpc_log(process: subprocess.Popen, runtime_info: FRPCRuntimeInfo):
"""异步监控 frpc 日志"""
logger.info("启动异步日志监控")
print("\n=== frpc 运行日志 (按 Ctrl+C 停止) ===")
print(f"{bcolors.WARNING}自动重启已启用,最大重启次数: {runtime_info.max_restarts}{bcolors.ENDC}")
print("-" * 80)
def read_output():
error_buffer = []
while not runtime_info.stop_flag and process.poll() is None:
if process.stdout:
try:
line = process.stdout.readline()
if line:
line_str = line.decode('utf-8', errors='ignore').strip()
runtime_info.log_buffer.append(line_str)
# 收集错误信息
if any(keyword in line_str.lower() for keyword in ['error', 'failed', 'fatal']):
error_buffer.append(line_str)
runtime_info.last_error = line_str
logger.error(f"FRPC运行错误: {line_str}")
# 日志级别高亮
timestamp = datetime.now().strftime('%H:%M:%S')
if 'error' in line_str.lower():
print(f"{bcolors.FAIL}{timestamp} {line_str}{bcolors.ENDC}")
elif 'warning' in line_str.lower():
print(f"{bcolors.WARNING}{timestamp} {line_str}{bcolors.ENDC}")
elif 'success' in line_str.lower() or 'start' in line_str.lower():
print(f"{bcolors.OKGREEN}{timestamp} {line_str}{bcolors.ENDC}")
else:
print(f"{timestamp} {line_str}")
logger.debug(f"FRPC日志: {line_str}")
except Exception as e:
logger.error(f"读取日志失败: {e}")
# 修复:添加退出条件,避免死循环
if runtime_info.stop_flag:
break
# 保存最后的错误信息
if error_buffer:
runtime_info.last_error = '\n'.join(error_buffer[-5:])
# 启动日志读取线程
log_thread = threading.Thread(target=read_output, daemon=True)
log_thread.start()
# 异步等待进程结束
while not runtime_info.stop_flag and process.poll() is None:
await asyncio.sleep(1)
# 修复:优雅停止日志线程
runtime_info.stop_flag = True
log_thread.join(timeout=5)
logger.info("日志监控结束")
async def async_start_frpc(config_file: str, generate_script: bool = False):
"""异步启动 frpc (带自动重启)"""
clear_screen()
print(f"=== 启动 frpc - 配置: {config_file} ===")
logger.info(f"启动FRPC,配置文件: {config_file}")
# 检查配置文件权限
check_file_permissions(config_file)
# 初始化运行时信息
runtime_info = FRPCRuntimeInfo(
max_restarts=3,
restart_delay=5
)
# 检查 frpc 是否存在
frpc_exec = "frpc.exe" if platform.system() == "Windows" else "./frpc"
if not Path(frpc_exec).exists():
print(f"{bcolors.WARNING}未找到 frpc 可执行文件{bcolors.ENDC}")
logger.warning("未找到FRPC可执行文件")
download = input("是否自动下载?(y/n): ").strip().lower()
if download == 'y':
if await async_download_frpc():
frpc_exec = "frpc.exe" if platform.system() == "Windows" else "./frpc"
else:
logger.error("FRPC下载失败")
return
else:
custom_path = input("请输入 frpc 路径: ").strip()
if Path(custom_path).exists():
frpc_exec = custom_path
else:
print(f"{bcolors.FAIL}路径无效{bcolors.ENDC}")
logger.error(f"FRPC路径无效: {custom_path}")
return
# 生成启动脚本
if generate_script:
script_ext = ".bat" if platform.system() == "Windows" else ".sh"
script_name = f"start_frpc_{Path(config_file).stem}{script_ext}"
try:
async with aiofiles.open(script_name, 'w', encoding='utf-8') as f:
if platform.system() == "Windows":
await f.write(f'@echo off\n"{frpc_exec}" -c "{config_file}"\npause')
else:
await f.write(f'#!/bin/bash\nchmod +x {frpc_exec}\n./{frpc_exec} -c {config_file}')
if platform.system() != "Windows":
os.chmod(script_name, 0o755)
print(f"{bcolors.OKGREEN}启动脚本已生成: {script_name}{bcolors.ENDC}")
logger.info(f"生成启动脚本: {script_name}")
# 修复:只生成脚本不启动frpc
return
except Exception as e:
logger.error(f"生成启动脚本失败: {e}")
# 询问运行模式
print("\n请选择运行模式:")
print("1. 前台运行 (随主程序结束一起结束)")
print("2. 后台运行 (与主程序脱离,需手动结束进程)")
while True:
mode_choice = input("请输入数字选择: ").strip()
if mode_choice in ['1', '2']:
run_in_background = mode_choice == '2'
break
else:
print(f"{bcolors.WARNING}请输入有效的数字 (1-2){bcolors.ENDC}")
if run_in_background:
print(f"\n{bcolors.OKBLUE}后台运行模式: frpc 将在后台运行,与主程序脱离{bcolors.ENDC}")
logger.info("用户选择后台运行模式")
# 启动后台进程
cmd = [frpc_exec, "-c", config_file]
print(f"启动命令: {' '.join(cmd)}")
# 跨平台后台运行
try:
if platform.system() == "Windows":
# Windows 后台运行
creation_flags = subprocess.CREATE_NEW_PROCESS_GROUP | subprocess.DETACHED_PROCESS
subprocess.Popen(
cmd,
creationflags=creation_flags
)
else:
# Linux/macOS 后台运行
subprocess.Popen(
cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
stdin=subprocess.DEVNULL,
close_fds=True,
start_new_session=True
)
print(f"{bcolors.OKGREEN}frpc 已在后台启动{bcolors.ENDC}")
print(f"{bcolors.WARNING}注意: 后台运行的 frpc 不会随主程序结束而结束,请手动结束进程{bcolors.ENDC}")
logger.info("FRPC已在后台启动")
return
except Exception as e:
logger.error(f"启动后台进程失败: {e}", exc_info=True)
print(f"{bcolors.FAIL}启动失败: {e}{bcolors.ENDC}")
return
# 前台运行模式
print(f"\n{bcolors.OKBLUE}前台运行模式: frpc 将随主程序结束一起结束{bcolors.ENDC}")
logger.info("用户选择前台运行模式")
# 主启动循环
try:
while not runtime_info.stop_flag and runtime_info.restart_count < runtime_info.max_restarts:
try:
cmd = [frpc_exec, "-c", config_file]
print(f"\n{bcolors.OKBLUE}启动命令: {' '.join(cmd)}{bcolors.ENDC}")
if runtime_info.restart_count > 0:
print(f"{bcolors.WARNING}自动重启 {runtime_info.restart_count}/{runtime_info.max_restarts} 次{bcolors.ENDC}")
logger.warning(f"FRPC异常退出,自动重启 {runtime_info.restart_count}/{runtime_info.max_restarts} 次")
# 修复:跨平台兼容的subprocess参数
creation_flags = 0
if platform.system() == "Windows":
creation_flags = subprocess.CREATE_NO_WINDOW
# 启动进程
runtime_info.process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
creationflags=creation_flags
)
# 异步监控日志
await async_monitor_frpc_log(runtime_info.process, runtime_info)
# 检查退出状态
exit_code = runtime_info.process.poll()
if exit_code is not None and exit_code != 0 and not runtime_info.stop_flag:
runtime_info.restart_count += 1
logger.error(f"FRPC异常退出,退出码: {exit_code}")
# 达到最大重启次数
if runtime_info.restart_count >= runtime_info.max_restarts:
print(f"\n{bcolors.FAIL}=== 达到最大重启次数,停止重启 ==={bcolors.ENDC}")
logger.error("达到最大重启次数,停止FRPC重启")
# 错误分析
await async_analyze_and_report_errors(runtime_info, config_file)
break
# 继续重启
print(f"\n{bcolors.WARNING}frpc 异常退出,{runtime_info.restart_delay} 秒后自动重启...{bcolors.ENDC}")
await asyncio.sleep(runtime_info.restart_delay)
except Exception as e:
logger.error(f"启动FRPC失败: {e}", exc_info=True)
print(f"{bcolors.FAIL}启动失败: {e}{bcolors.ENDC}")
runtime_info.restart_count += 1
if runtime_info.restart_count < runtime_info.max_restarts:
await asyncio.sleep(runtime_info.restart_delay)
else:
break
except KeyboardInterrupt:
# 修复:捕获Ctrl+C,优雅停止
runtime_info.stop_flag = True
if runtime_info.process and runtime_info.process.poll() is None:
runtime_info.process.terminate()
print(f"\n{bcolors.WARNING}用户中断,正在停止frpc...{bcolors.ENDC}")
print(f"\n{bcolors.OKGREEN}frpc 进程已终止{bcolors.ENDC}")
logger.info("FRPC进程已终止")
async def async_analyze_and_report_errors(runtime_info: FRPCRuntimeInfo, config_file: str):
"""异步分析错误并生成报告"""
print(f"\n{bcolors.HEADER}=== 错误分析报告 ==={bcolors.ENDC}")
# 分析错误
log_content = '\n'.join(runtime_info.log_buffer)
analysis = analyze_frpc_error(log_content or runtime_info.last_error)
# 显示分析结果
print(f"错误类型: {bcolors.FAIL}{analysis['error_type']}{bcolors.ENDC}")
print(f"问题描述: {analysis['description']}")
if analysis['matched_text']:
print(f"关键错误: {bcolors.WARNING}{analysis['matched_text']}{bcolors.ENDC}")
print(f"\n{bcolors.OKBLUE}解决方案:{bcolors.ENDC}")
for i, solution in enumerate(analysis['solutions'], 1):
print(f" {i}. {solution}")
# 异步保存日志
log_file = f"frpc_error_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
try:
async with aiofiles.open(log_file, 'w', encoding='utf-8') as f:
await f.write(f"FRPC 错误日志 - {datetime.now()}\n")
await f.write(f"配置文件: {config_file}\n")
await f.write(f"重启次数: {runtime_info.restart_count}\n")
await f.write(f"最后错误: {runtime_info.last_error}\n")
await f.write("=" * 80 + "\n\n")
await f.write(log_content)
print(f"\n{bcolors.OKCYAN}完整日志已保存到: {log_file}{bcolors.ENDC}")
logger.info(f"错误日志已保存: {log_file}")
except Exception as e:
logger.error(f"保存错误日志失败: {e}")
async def async_download_frpc(max_retries: int = 3, timeout: int = 30) -> bool:
"""异步下载FRPC(带重试和超时)"""
clear_screen()
print("=== 自动下载 frpc 客户端 ===")
logger.info("开始下载FRPC客户端")
# 检测系统
system = platform.system().lower()
arch = platform.machine().lower()
# 映射系统架构
download_mapping = {
'windows': ('windows_amd64', 'frpc.exe', True),
'linux': ('linux_amd64', 'frpc', False),
'darwin': ('darwin_arm64' if arch in ['arm64', 'aarch64'] else 'darwin_amd64', 'frpc', False)
}
if system not in download_mapping:
print(f"{bcolors.FAIL}不支持的系统: {system}{bcolors.ENDC}")
logger.error(f"不支持的系统: {system}")
return False
download_key, frpc_file, is_zip = download_mapping[system]
# 检查是否已存在
if Path(frpc_file).exists():
overwrite = input(f"\n{frpc_file} 已存在,是否覆盖?(y/n): ").strip().lower()
if overwrite != 'y':
return True
# 下载文件(带重试)
original_url = FRPC_DOWNLOAD_URLS[download_key]
# GitHub 代理列表
proxy_options = [
{"name": "原始 GitHub 地址", "url": original_url},
{"name": "gh-proxy.org (IPv4)", "url": f"https://gh-proxy.org/{original_url.replace('https://', '')}"},
{"name": "v6.gh-proxy.org (IPv6)", "url": f"https://v6.gh-proxy.org/{original_url.replace('https://', '')}"},
{"name": "hk.gh-proxy.org", "url": f"https://hk.gh-proxy.org/{original_url.replace('https://', '')}"},
{"name": "cdn.gh-proxy.org", "url": f"https://cdn.gh-proxy.org/{original_url.replace('https://', '')}"},
{"name": "edgeone.gh-proxy.org", "url": f"https://edgeone.gh-proxy.org/{original_url.replace('https://', '')}"},
{"name": "在浏览器中打开下载", "url": original_url, "browser": True}
]
# 询问用户选择下载源
print("\n请选择下载源:")
for i, option in enumerate(proxy_options, 1):
print(f"{i}. {option['name']}")
while True:
choice = input("请输入数字选择: ").strip()
if choice.isdigit() and 1 <= int(choice) <= len(proxy_options):
selected_option = proxy_options[int(choice) - 1]
selected_url = selected_option["url"]
selected_name = selected_option["name"]
# 检查是否需要在浏览器中打开
if selected_option.get("browser", False):
print(f"\n已选择: {selected_name}")
print(f"下载地址: {selected_url}")
logger.info(f"用户选择在浏览器中打开下载: {selected_url}")
# 尝试打开浏览器
try:
import webbrowser
webbrowser.open(selected_url)
print(f"{bcolors.OKGREEN}浏览器已打开,请在浏览器中完成下载{bcolors.ENDC}")
except Exception as e:
logger.error(f"打开浏览器失败: {e}")
print(f"{bcolors.WARNING}无法自动打开浏览器,请手动访问上述地址{bcolors.ENDC}")
# 指导用户接下来的操作
print("\n接下来的操作步骤:")
print("1. 在浏览器中完成下载")
print(f"2. 找到下载的文件 ({os.path.basename(original_url)})")
print(f"3. 将文件解压到当前目录")
print(f"4. 确保 {frpc_file} 被提取到当前目录")
print("5. 回到本程序继续操作")
input("\n当你完成上述步骤后,按 Enter 键继续...")
return True
else:
print(f"\n已选择: {selected_name}")
print(f"下载地址: {selected_url}")
logger.info(f"用户选择下载源: {selected_name}, 地址: {selected_url}")
break
else:
print(f"{bcolors.WARNING}请输入有效的数字 (1-{len(proxy_options)}){bcolors.ENDC}")
temp_file = None
try:
for retry in range(max_retries):
try: