-
Notifications
You must be signed in to change notification settings - Fork 944
Expand file tree
/
Copy pathnginx-hysteria2.py
More file actions
3798 lines (3242 loc) · 146 KB
/
Copy pathnginx-hysteria2.py
File metadata and controls
3798 lines (3242 loc) · 146 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
import os
import sys
import json
import ssl
import shutil
import platform
import urllib.request
import urllib.parse
import subprocess
import socket
import time
import argparse
from pathlib import Path
import base64
import random
def get_user_home():
"""获取用户主目录"""
return str(Path.home())
def get_system_info():
"""获取系统信息"""
system = platform.system().lower()
machine = platform.machine().lower()
# 系统映射
os_map = {
'linux': 'linux',
'darwin': 'darwin', # macOS
'windows': 'windows'
}
# 架构映射
arch_map = {
'x86_64': 'amd64',
'amd64': 'amd64',
'aarch64': 'arm64',
'arm64': 'arm64',
'i386': '386',
'i686': '386'
}
os_name = os_map.get(system, 'linux')
arch = arch_map.get(machine, 'amd64')
return os_name, arch
def ensure_nginx_user():
"""确保nginx用户存在,如果不存在就创建,统一使用nginx用户"""
try:
# 检查nginx用户是否已存在
try:
result = subprocess.run(['id', 'nginx'], check=True, capture_output=True, text=True)
if result.returncode == 0:
print("✅ nginx用户已存在")
return 'nginx'
except:
# nginx用户不存在,创建它
print("🔧 nginx用户不存在,正在创建...")
# 创建nginx系统用户(无登录shell,无家目录)
try:
subprocess.run([
'sudo', 'useradd',
'--system', # 系统用户
'--no-create-home', # 不创建家目录
'--shell', '/bin/false', # 无登录shell
'--comment', 'nginx web server', # 注释
'nginx'
], check=True, capture_output=True)
print("✅ nginx用户创建成功")
return 'nginx'
except subprocess.CalledProcessError as e:
# 如果创建失败,可能是因为用户已存在但id命令失败,或其他原因
print(f"⚠️ 创建nginx用户失败: {e}")
# 再次检查用户是否存在(可能是并发创建)
try:
subprocess.run(['id', 'nginx'], check=True, capture_output=True)
print("✅ nginx用户实际上已存在")
return 'nginx'
except:
# 确实创建失败,fallback到root用户
print("⚠️ 使用root用户作为nginx运行用户")
return 'root'
except Exception as e:
print(f"❌ 处理nginx用户时出错: {e}")
# 出错时使用root用户
return 'root'
def set_nginx_permissions(web_dir):
"""设置nginx目录的正确权限"""
try:
nginx_user = ensure_nginx_user()
print(f"🔧 设置目录权限: {web_dir}")
print(f"👤 使用用户: {nginx_user}")
# 设置目录和文件权限
subprocess.run(['sudo', 'chown', '-R', f'{nginx_user}:{nginx_user}', web_dir], check=True)
subprocess.run(['sudo', 'chmod', '-R', '755', web_dir], check=True)
subprocess.run(['sudo', 'find', web_dir, '-type', 'f', '-exec', 'chmod', '644', '{}', ';'], check=True)
print(f"✅ 权限设置完成: {web_dir} (用户: {nginx_user})")
return True
except Exception as e:
print(f"❌ 设置权限失败: {e}")
return False
def check_port_available(port):
"""检查端口是否可用(仅使用socket)"""
try:
# 对于Hysteria2,我们主要关心UDP端口
# nginx使用TCP端口,hysteria使用UDP端口,它们可以共存
# 检查UDP端口是否可用(这是hysteria2需要的)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.settimeout(1)
try:
s.bind(('', port))
return True # UDP端口可用
except:
# UDP端口被占用,检查是否是hysteria进程
return False
except:
# 如果有任何异常,保守起见返回端口不可用
return False
def is_port_listening(port):
"""检查端口是否已经在监听(服务是否已启动)"""
try:
# 尝试连接到端口
# 由于 Hysteria 使用 UDP,我们检查 UDP 端口
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(1)
# 尝试发送一个数据包到端口
# 如果端口打开,send不会抛出异常
try:
sock.sendto(b"ping", ('127.0.0.1', port))
try:
sock.recvfrom(1024) # 尝试接收响应
return True
except socket.timeout:
# 没收到响应但也没报错,可能仍在监听
return True
except:
pass
# 另一种检查方式:尝试绑定端口,如果失败说明端口已被占用
try:
test_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
test_sock.bind(('', port))
test_sock.close()
return False # 能成功绑定说明端口未被占用
except:
return True # 无法绑定说明端口已被占用
return False
except:
return False
finally:
try:
sock.close()
except:
pass
def check_process_running(pid_file):
"""检查进程是否在运行"""
if not os.path.exists(pid_file):
return False
try:
with open(pid_file, 'r') as f:
pid = f.read().strip()
if not pid:
return False
# 尝试发送信号0检查进程是否存在
try:
os.kill(int(pid), 0)
return True
except:
return False
except:
return False
def create_directories():
"""创建必要的目录"""
home = get_user_home()
dirs = [
f"{home}/.hysteria2",
f"{home}/.hysteria2/cert",
f"{home}/.hysteria2/config",
f"{home}/.hysteria2/logs"
]
for d in dirs:
os.makedirs(d, exist_ok=True)
return dirs[0]
def download_file(url, save_path, max_retries=3):
"""下载文件,带重试机制"""
for i in range(max_retries):
try:
print(f"正在下载... (尝试 {i+1}/{max_retries})")
urllib.request.urlretrieve(url, save_path)
return True
except Exception as e:
print(f"下载失败: {e}")
if i < max_retries - 1:
time.sleep(2) # 等待2秒后重试
continue
return False
def get_latest_version():
"""返回固定的最新版本号 v2.6.1"""
return "v2.6.1"
def get_download_filename(os_name, arch):
"""根据系统和架构返回正确的文件名"""
# windows 需要 .exe
if os_name == 'windows':
if arch == 'amd64':
return 'hysteria-windows-amd64.exe'
elif arch == '386':
return 'hysteria-windows-386.exe'
elif arch == 'arm64':
return 'hysteria-windows-arm64.exe'
else:
return f'hysteria-windows-{arch}.exe'
else:
return f'hysteria-{os_name}-{arch}'
def verify_binary(binary_path):
"""验证二进制文件是否有效(简化版)"""
try:
# 检查文件是否存在
if not os.path.exists(binary_path):
return False
# 检查文件大小(至少5MB - hysteria一般大于10MB)
if os.path.getsize(binary_path) < 5 * 1024 * 1024:
return False
# 设置文件为可执行
os.chmod(binary_path, 0o755)
# 返回成功
return True
except:
return False
def download_hysteria2(base_dir):
"""下载Hysteria2二进制文件,使用简化链接和验证方式"""
try:
version = get_latest_version()
os_name, arch = get_system_info()
filename = get_download_filename(os_name, arch)
# 只使用原始GitHub链接,避免镜像问题
url = f"https://github.com/apernet/hysteria/releases/download/app/{version}/{filename}"
binary_path = f"{base_dir}/hysteria"
if os_name == 'windows':
binary_path += '.exe'
print(f"正在下载 Hysteria2 {version}...")
print(f"系统类型: {os_name}, 架构: {arch}, 文件名: {filename}")
print(f"下载链接: {url}")
# 使用wget下载
try:
has_wget = shutil.which('wget') is not None
has_curl = shutil.which('curl') is not None
if has_wget:
print("使用wget下载...")
subprocess.run(['wget', '--tries=3', '--timeout=15', '-O', binary_path, url], check=True)
elif has_curl:
print("使用curl下载...")
subprocess.run(['curl', '-L', '--connect-timeout', '15', '-o', binary_path, url], check=True)
else:
print("系统无wget/curl,尝试使用Python下载...")
urllib.request.urlretrieve(url, binary_path)
# 验证下载
if not verify_binary(binary_path):
raise Exception("下载的文件无效")
print(f"下载成功: {binary_path}, 大小: {os.path.getsize(binary_path)/1024/1024:.2f}MB")
return binary_path, version
except Exception as e:
print(f"自动下载失败: {e}")
print("请按照以下步骤手动下载:")
print(f"1. 访问 https://github.com/apernet/hysteria/releases/tag/app/{version}")
print(f"2. 下载 {filename} 文件")
print(f"3. 将文件重命名为 hysteria (不要加后缀) 并移动到 {base_dir}/ 目录")
print(f"4. 执行: chmod +x {base_dir}/hysteria")
# 询问用户文件是否已放置
while True:
user_input = input("已完成手动下载和放置? (y/n): ").lower()
if user_input == 'y':
# 检查文件是否存在
if os.path.exists(binary_path) and verify_binary(binary_path):
print("文件验证成功,继续安装...")
return binary_path, version
else:
print(f"文件不存在或无效,请确保放在 {binary_path} 位置。")
elif user_input == 'n':
print("中止安装。")
sys.exit(1)
except Exception as e:
print(f"下载错误: {e}")
sys.exit(1)
def get_ip_address():
"""获取本机IP地址(优先获取公网IP,如果失败则使用本地IP)"""
# 首先尝试获取公网IP
try:
# 尝试从公共API获取公网IP
with urllib.request.urlopen('https://api.ipify.org', timeout=5) as response:
public_ip = response.read().decode('utf-8')
if public_ip and len(public_ip) > 0:
return public_ip
except:
try:
# 备选API
with urllib.request.urlopen('https://ifconfig.me', timeout=5) as response:
public_ip = response.read().decode('utf-8')
if public_ip and len(public_ip) > 0:
return public_ip
except:
pass
# 如果获取公网IP失败,尝试获取本地IP
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 不需要真正连接,只是获取路由信息
s.connect(('8.8.8.8', 80))
local_ip = s.getsockname()[0]
s.close()
return local_ip
except:
# 如果所有方法都失败,返回本地回环地址
return '127.0.0.1'
def setup_nginx_smart_proxy(base_dir, domain, web_dir, cert_path, key_path, hysteria_port):
"""设置nginx Web伪装:TCP端口显示正常网站,UDP端口用于Hysteria2"""
print("🚀 正在配置nginx Web伪装...")
try:
# 检查证书文件
print(f"🔍 检查证书文件路径:")
print(f"证书文件: {cert_path}")
print(f"密钥文件: {key_path}")
if not os.path.exists(cert_path):
print(f"❌ 证书文件不存在: {cert_path}")
cert_path, key_path = generate_self_signed_cert(base_dir, domain)
if not os.path.exists(key_path):
print(f"❌ 密钥文件不存在: {key_path}")
cert_path, key_path = generate_self_signed_cert(base_dir, domain)
print(f"📁 最终使用的证书路径:")
print(f"证书: {cert_path}")
print(f"密钥: {key_path}")
# 确保nginx用户存在
nginx_user = ensure_nginx_user()
print(f"👤 使用nginx用户: {nginx_user}")
# 创建nginx标准Web配置
nginx_conf = f"""user {nginx_user};
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /run/nginx.pid;
events {{
worker_connections 1024;
}}
http {{
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server_tokens off;
server {{
listen 80;
listen 443 ssl http2;
server_name _;
ssl_certificate {os.path.abspath(cert_path)};
ssl_certificate_key {os.path.abspath(key_path)};
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
root {web_dir};
index index.html index.htm;
# 正常网站访问
location / {{
try_files $uri $uri/ /index.html;
}}
add_header X-Frame-Options DENY always;
add_header X-Content-Type-Options nosniff always;
}}
}}"""
# 更新nginx配置
print("💾 备份当前nginx配置...")
subprocess.run(['sudo', 'cp', '/etc/nginx/nginx.conf', '/etc/nginx/nginx.conf.backup'], check=True)
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.conf') as tmp:
tmp.write(nginx_conf)
tmp.flush()
subprocess.run(['sudo', 'cp', tmp.name, '/etc/nginx/nginx.conf'], check=True)
os.unlink(tmp.name)
subprocess.run(['sudo', 'rm', '-f', '/etc/nginx/conf.d/*.conf'], check=True)
# 测试并重启
print("🔧 测试nginx配置...")
test_result = subprocess.run(['sudo', 'nginx', '-t'], capture_output=True, text=True)
if test_result.returncode != 0:
print(f"❌ nginx配置测试失败:")
print(f"错误信息: {test_result.stderr}")
subprocess.run(['sudo', 'cp', '/etc/nginx/nginx.conf.backup', '/etc/nginx/nginx.conf'], check=True)
print("🔄 已恢复nginx配置备份")
return False, None
print("✅ nginx配置测试通过")
print("🔄 重启nginx服务...")
restart_result = subprocess.run(['sudo', 'systemctl', 'restart', 'nginx'], capture_output=True, text=True)
if restart_result.returncode != 0:
print(f"❌ nginx重启失败:")
print(f"错误信息: {restart_result.stderr}")
return False, None
print("✅ nginx Web伪装配置成功!")
print("🎯 TCP端口: 标准HTTPS网站")
print("🎯 UDP端口: Hysteria2代理服务")
return True, hysteria_port
except Exception as e:
print(f"❌ 配置失败: {e}")
return False, None
def create_web_masquerade(base_dir):
"""创建Web伪装页面"""
web_dir = f"{base_dir}/web"
os.makedirs(web_dir, exist_ok=True)
return create_web_files_in_directory(web_dir)
def create_web_files_in_directory(web_dir):
"""在指定目录创建Web文件"""
# 确保目录存在
if not os.path.exists(web_dir):
try:
subprocess.run(['sudo', 'mkdir', '-p', web_dir], check=True)
except:
os.makedirs(web_dir, exist_ok=True)
# 创建一个更逼真的企业网站首页
index_html = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Global Digital Solutions - Enterprise Cloud Services</title>
<meta name="description" content="Leading provider of enterprise cloud solutions, digital infrastructure, and business technology services.">
<meta name="keywords" content="cloud computing, enterprise solutions, digital transformation, IT services">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; line-height: 1.6; color: #333; background: #f8f9fa; }
.container { max-width: 1200px; margin: 0 auto; padding: 0 20px; }
header { background: linear-gradient(135deg, #2c5aa0 0%, #1e3a8a 100%); color: white; padding: 1rem 0; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
nav { display: flex; justify-content: space-between; align-items: center; }
.logo { font-size: 1.8rem; font-weight: bold; }
.nav-links { display: flex; list-style: none; gap: 2rem; }
.nav-links a { color: white; text-decoration: none; transition: opacity 0.3s; font-weight: 500; }
.nav-links a:hover { opacity: 0.8; }
.hero { background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%); padding: 5rem 0; text-align: center; }
.hero h1 { font-size: 3.5rem; margin-bottom: 1rem; color: #1e293b; font-weight: 700; }
.hero p { font-size: 1.3rem; color: #64748b; margin-bottom: 2.5rem; max-width: 600px; margin-left: auto; margin-right: auto; }
.btn { display: inline-block; background: #2563eb; color: white; padding: 15px 35px; text-decoration: none; border-radius: 8px; transition: all 0.3s; font-weight: 600; margin: 0 10px; }
.btn:hover { background: #1d4ed8; transform: translateY(-2px); }
.btn-secondary { background: transparent; border: 2px solid #2563eb; color: #2563eb; }
.btn-secondary:hover { background: #2563eb; color: white; }
.stats { background: white; padding: 3rem 0; }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 2rem; text-align: center; }
.stat h3 { font-size: 2.5rem; color: #2563eb; font-weight: 700; }
.stat p { color: #64748b; font-weight: 500; }
.features { padding: 5rem 0; background: #f8fafc; }
.features h2 { text-align: center; font-size: 2.5rem; margin-bottom: 3rem; color: #1e293b; }
.features-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 3rem; margin-top: 3rem; }
.feature { background: white; padding: 2.5rem; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); text-align: center; transition: transform 0.3s; }
.feature:hover { transform: translateY(-5px); }
.feature-icon { font-size: 3rem; margin-bottom: 1rem; }
.feature h3 { color: #1e293b; margin-bottom: 1rem; font-size: 1.3rem; }
.feature p { color: #64748b; line-height: 1.7; }
.cta { background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%); color: white; padding: 5rem 0; text-align: center; }
.cta h2 { font-size: 2.5rem; margin-bottom: 1rem; }
.cta p { font-size: 1.2rem; margin-bottom: 2rem; opacity: 0.9; }
footer { background: #1e293b; color: white; text-align: center; padding: 3rem 0; }
.footer-content { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 2rem; margin-bottom: 2rem; text-align: left; }
.footer-section h4 { margin-bottom: 1rem; color: #3b82f6; }
.footer-section p, .footer-section a { color: #94a3b8; text-decoration: none; }
.footer-section a:hover { color: white; }
.footer-bottom { border-top: 1px solid #334155; padding-top: 2rem; margin-top: 2rem; text-align: center; color: #94a3b8; }
</style>
</head>
<body>
<header>
<nav class="container">
<div class="logo">Global Digital Solutions</div>
<ul class="nav-links">
<li><a href="#home">Home</a></li>
<li><a href="#services">Solutions</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<section class="hero">
<div class="container">
<h1>Transform Your Digital Future</h1>
<p>Leading enterprise cloud solutions and digital infrastructure services for businesses worldwide. Secure, scalable, and always available.</p>
<a href="#services" class="btn">Explore Solutions</a>
<a href="#contact" class="btn btn-secondary">Get Started</a>
</div>
</section>
<section class="stats">
<div class="container">
<div class="stats-grid">
<div class="stat">
<h3>99.9%</h3>
<p>Uptime Guarantee</p>
</div>
<div class="stat">
<h3>10,000+</h3>
<p>Enterprise Clients</p>
</div>
<div class="stat">
<h3>50+</h3>
<p>Global Data Centers</p>
</div>
<div class="stat">
<h3>24/7</h3>
<p>Expert Support</p>
</div>
</div>
</div>
</section>
<section class="features" id="services">
<div class="container">
<h2>Enterprise Cloud Solutions</h2>
<div class="features-grid">
<div class="feature">
<div class="feature-icon">☁️</div>
<h3>Cloud Infrastructure</h3>
<p>Scalable and secure cloud infrastructure with global reach. Deploy your applications with confidence on our enterprise-grade platform.</p>
</div>
<div class="feature">
<div class="feature-icon">🔒</div>
<h3>Security & Compliance</h3>
<p>Advanced security protocols and compliance standards including SOC 2, ISO 27001, and GDPR to protect your business data.</p>
</div>
<div class="feature">
<div class="feature-icon">⚡</div>
<h3>High Performance</h3>
<p>Lightning-fast performance with our global CDN network and optimized infrastructure for maximum speed and reliability.</p>
</div>
<div class="feature">
<div class="feature-icon">📊</div>
<h3>Analytics & Monitoring</h3>
<p>Real-time monitoring and detailed analytics to help you optimize performance and make data-driven business decisions.</p>
</div>
<div class="feature">
<div class="feature-icon">🛠️</div>
<h3>Managed Services</h3>
<p>Full-stack managed services including database management, security updates, and performance optimization by our experts.</p>
</div>
<div class="feature">
<div class="feature-icon">🌍</div>
<h3>Global Reach</h3>
<p>Worldwide infrastructure with data centers across six continents, ensuring low latency and high availability for your users.</p>
</div>
</div>
</div>
</section>
<section class="cta" id="contact">
<div class="container">
<h2>Ready to Transform Your Business?</h2>
<p>Join thousands of enterprises already using our cloud solutions</p>
<a href="mailto:contact@globaldigi.com" class="btn">Contact Sales Team</a>
</div>
</section>
<footer>
<div class="container">
<div class="footer-content">
<div class="footer-section">
<h4>Solutions</h4>
<p><a href="#">Cloud Infrastructure</a></p>
<p><a href="#">Security Services</a></p>
<p><a href="#">Data Analytics</a></p>
<p><a href="#">Managed Services</a></p>
</div>
<div class="footer-section">
<h4>Company</h4>
<p><a href="#">About Us</a></p>
<p><a href="#">Careers</a></p>
<p><a href="#">News</a></p>
<p><a href="#">Contact</a></p>
</div>
<div class="footer-section">
<h4>Support</h4>
<p><a href="#">Documentation</a></p>
<p><a href="#">Help Center</a></p>
<p><a href="#">Status Page</a></p>
<p><a href="#">Contact Support</a></p>
</div>
<div class="footer-section">
<h4>Legal</h4>
<p><a href="#">Privacy Policy</a></p>
<p><a href="#">Terms of Service</a></p>
<p><a href="#">Security</a></p>
<p><a href="#">Compliance</a></p>
</div>
</div>
<div class="footer-bottom">
<p>© 2024 Global Digital Solutions Inc. All rights reserved. | Enterprise Cloud Services</p>
</div>
</div>
</footer>
</body>
</html>"""
# 使用sudo写入文件(如果需要)
try:
with open(f"{web_dir}/index.html", "w", encoding="utf-8") as f:
f.write(index_html)
except PermissionError:
# 使用sudo写入
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.html') as tmp:
tmp.write(index_html)
tmp.flush()
subprocess.run(['sudo', 'cp', tmp.name, f"{web_dir}/index.html"], check=True)
os.unlink(tmp.name)
# 创建robots.txt(看起来更真实)
robots_txt = """User-agent: *
Allow: /
Sitemap: /sitemap.xml
"""
try:
with open(f"{web_dir}/robots.txt", "w") as f:
f.write(robots_txt)
except PermissionError:
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as tmp:
tmp.write(robots_txt)
tmp.flush()
subprocess.run(['sudo', 'cp', tmp.name, f"{web_dir}/robots.txt"], check=True)
os.unlink(tmp.name)
# 创建sitemap.xml
sitemap_xml = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>/</loc>
<lastmod>2024-01-01</lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>/services</loc>
<lastmod>2024-01-01</lastmod>
<changefreq>monthly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>/about</loc>
<lastmod>2024-01-01</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>/contact</loc>
<lastmod>2024-01-01</lastmod>
<changefreq>monthly</changefreq>
<priority>0.7</priority>
</url>
</urlset>"""
try:
with open(f"{web_dir}/sitemap.xml", "w") as f:
f.write(sitemap_xml)
except PermissionError:
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.xml') as tmp:
tmp.write(sitemap_xml)
tmp.flush()
subprocess.run(['sudo', 'cp', tmp.name, f"{web_dir}/sitemap.xml"], check=True)
os.unlink(tmp.name)
# 创建favicon.ico (简单的base64编码)
# 这是一个简单的蓝色圆形图标
favicon_data = """AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAABILAAASCwAAAAAAAAAAAAD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A2dnZ/9nZ2f/Z2dn/2dnZ/9nZ2f/Z2dn/2dnZ/9nZ2f/Z2dn/2dnZ/////wD///8A////AP///wD///8A2dnZ/1tbW/8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/1tbW//Z2dn/////AP///wD///8A2dnZ/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/2dnZ/////wD///8A2dnZ/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/2dnZ/////wD///8A2dnZ/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/2dnZ/////wD///8A2dnZ/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/2dnZ/////wD///8A2dnZ/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/2dnZ/////wD///8A2dnZ/1tbW/8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/1tbW//Z2dn/////AP///wD///8A////AP///wD///8A2dnZ/9nZ2f/Z2dn/2dnZ/9nZ2f/Z2dn/2dnZ/9nZ2f/Z2dn/2dnZ/////wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A////AP///wD///8A//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAP//AAD//wAA//8AAA=="""
import base64
try:
favicon_bytes = base64.b64decode(favicon_data)
try:
with open(f"{web_dir}/favicon.ico", "wb") as f:
f.write(favicon_bytes)
except PermissionError:
import tempfile
with tempfile.NamedTemporaryFile(delete=False, suffix='.ico') as tmp:
tmp.write(favicon_bytes)
tmp.flush()
subprocess.run(['sudo', 'cp', tmp.name, f"{web_dir}/favicon.ico"], check=True)
os.unlink(tmp.name)
except:
pass # 如果favicon创建失败就跳过
# 创建about页面
about_html = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>About Us - Global Digital Solutions</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div style="text-align: center; padding: 50px; font-family: Arial, sans-serif;">
<h1>About Global Digital Solutions</h1>
<p>We are a leading provider of enterprise cloud solutions, serving businesses worldwide since 2015.</p>
<p>Our mission is to transform how businesses operate in the digital age through innovative cloud technologies.</p>
<p><a href="/">← Back to Home</a></p>
</div>
</body>
</html>"""
try:
with open(f"{web_dir}/about.html", "w", encoding="utf-8") as f:
f.write(about_html)
except PermissionError:
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.html') as tmp:
tmp.write(about_html)
tmp.flush()
subprocess.run(['sudo', 'cp', tmp.name, f"{web_dir}/about.html"], check=True)
os.unlink(tmp.name)
# 创建404页面
error_html = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>404 - Page Not Found</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; padding: 50px; background: #f4f4f4; }
.error-container { background: white; padding: 50px; border-radius: 10px; box-shadow: 0 0 20px rgba(0,0,0,0.1); max-width: 500px; margin: 0 auto; }
h1 { color: #e74c3c; font-size: 4rem; margin-bottom: 1rem; }
p { color: #666; font-size: 1.2rem; }
a { color: #3498db; text-decoration: none; }
</style>
</head>
<body>
<div class="error-container">
<h1>404</h1>
<p>Sorry, the page you are looking for could not be found.</p>
<p><a href="/">Return to Homepage</a></p>
</div>
</body>
</html>"""
try:
with open(f"{web_dir}/404.html", "w", encoding="utf-8") as f:
f.write(error_html)
except PermissionError:
import tempfile
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.html') as tmp:
tmp.write(error_html)
tmp.flush()
subprocess.run(['sudo', 'cp', tmp.name, f"{web_dir}/404.html"], check=True)
os.unlink(tmp.name)
return web_dir
def generate_self_signed_cert(base_dir, domain):
"""生成自签名证书"""
cert_dir = f"{base_dir}/cert"
cert_path = f"{cert_dir}/server.crt"
key_path = f"{cert_dir}/server.key"
# 确保域名不为空,如果为空则使用默认值
if not domain or not domain.strip():
domain = "localhost"
print("警告: 域名为空,使用localhost作为证书通用名")
try:
# 生成更安全的证书
subprocess.run([
"openssl", "req", "-x509", "-nodes",
"-newkey", "rsa:4096", # 使用4096位密钥
"-keyout", key_path,
"-out", cert_path,
"-subj", f"/CN={domain}",
"-days", "36500",
"-sha256" # 使用SHA256
], check=True)
# 设置适当的权限
os.chmod(cert_path, 0o644)
os.chmod(key_path, 0o600)
return cert_path, key_path
except Exception as e:
print(f"生成证书失败: {e}")
sys.exit(1)
def get_real_certificate(base_dir, domain, email="admin@example.com"):
"""使用certbot获取真实的Let's Encrypt证书"""
cert_dir = f"{base_dir}/cert"
try:
# 检查是否已安装certbot
if not shutil.which('certbot'):
print("正在安装certbot...")
if platform.system().lower() == 'linux':
# Ubuntu/Debian
if shutil.which('apt'):
subprocess.run(['sudo', 'apt', 'update'], check=True)
subprocess.run(['sudo', 'apt', 'install', '-y', 'certbot'], check=True)
# CentOS/RHEL
elif shutil.which('yum'):
subprocess.run(['sudo', 'yum', 'install', '-y', 'certbot'], check=True)
elif shutil.which('dnf'):
subprocess.run(['sudo', 'dnf', 'install', '-y', 'certbot'], check=True)
else:
print("无法自动安装certbot,请手动安装")
return None, None
else:
print("请手动安装certbot")
return None, None
# 使用standalone模式获取证书
print(f"正在为域名 {domain} 获取Let's Encrypt证书...")
subprocess.run([
'sudo', 'certbot', 'certonly',
'--standalone',
'--agree-tos',
'--non-interactive',
'--email', email,
'-d', domain
], check=True)
# 复制证书到我们的目录
cert_source = f"/etc/letsencrypt/live/{domain}/fullchain.pem"
key_source = f"/etc/letsencrypt/live/{domain}/privkey.pem"
cert_path = f"{cert_dir}/server.crt"
key_path = f"{cert_dir}/server.key"
shutil.copy2(cert_source, cert_path)
shutil.copy2(key_source, key_path)
# 设置权限
os.chmod(cert_path, 0o644)
os.chmod(key_path, 0o600)
print(f"成功获取真实证书: {cert_path}")
return cert_path, key_path
except Exception as e:
print(f"获取真实证书失败: {e}")
print("将使用自签名证书作为备选...")
return None, None
def create_config(base_dir, port, password, cert_path, key_path, domain, enable_web_masquerade=True, custom_web_dir=None, enable_port_hopping=False, obfs_password=None, enable_http3_masquerade=False):
"""创建Hysteria2配置文件(端口跳跃、混淆、HTTP/3伪装)"""
# 基础配置
config = {
"listen": f":{port}",
"tls": {
"cert": cert_path,
"key": key_path
},
"auth": {
"type": "password",
"password": password
},
"bandwidth": {
"up": "1000 mbps",
"down": "1000 mbps"
},
"ignoreClientBandwidth": False,
"log": {
"level": "warn",
"output": f"{base_dir}/logs/hysteria.log",
"timestamp": True
},
"resolver": {
"type": "udp",
"tcp": {
"addr": "8.8.8.8:53",
"timeout": "4s"
},
"udp": {
"addr": "8.8.8.8:53",
"timeout": "4s"
}
}
}
# 端口跳跃配置 (Port Hopping)
if enable_port_hopping:
# Hysteria2服务器端只监听单个端口,端口跳跃通过iptables DNAT实现
port_start = max(1024, port - 25)
port_end = min(65535, port + 25)
# 确保范围合理:如果基准端口太小,使用固定范围
if port < 1049: # 1024 + 25
port_start = 1024
port_end = 1074
# 服务器仍然只监听单个端口
config["listen"] = f":{port}"
# 记录端口跳跃信息,用于后续iptables配置
config["_port_hopping"] = {
"enabled": True,
"range_start": port_start,
"range_end": port_end,
"listen_port": port
}
print(f"✅ 启用端口跳跃 - 服务器监听: {port}, 客户端可用范围: {port_start}-{port_end}")
# 流量混淆配置 (Salamander Obfuscation)
if obfs_password:
config["obfs"] = {
"type": "salamander",
"salamander": {
"password": obfs_password
}
}
print(f"✅ 启用Salamander混淆 - 密码: {obfs_password}")
# HTTP/3伪装配置
if enable_http3_masquerade:
if enable_web_masquerade and custom_web_dir and os.path.exists(custom_web_dir):
config["masquerade"] = {
"type": "file",
"file": {
"dir": custom_web_dir
}
}
else:
# 使用HTTP/3网站伪装
config["masquerade"] = {
"type": "proxy",
"proxy": {
"url": "https://www.google.com",
"rewriteHost": True
}
}
print("✅ 启用HTTP/3伪装 - 流量看起来像正常HTTP/3")
elif enable_web_masquerade and custom_web_dir and os.path.exists(custom_web_dir):
config["masquerade"] = {
"type": "file",
"file": {