Qilan2 commited on
Commit
ded1fa4
·
verified ·
1 Parent(s): f9e615e

Create jd.py

Browse files
Files changed (1) hide show
  1. hf-jg/jd.py +804 -0
hf-jg/jd.py ADDED
@@ -0,0 +1,804 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import json
4
+ import time
5
+ import base64
6
+ import shutil
7
+ import asyncio
8
+ import requests
9
+ import platform
10
+ import subprocess
11
+ import threading
12
+ from threading import Thread
13
+ from http.server import BaseHTTPRequestHandler, HTTPServer
14
+
15
+ # Environment variables
16
+ UPLOAD_URL = os.environ.get('UPLOAD_URL', '') # 节点或订阅上传地址,只填写这个地址将上传节点,同时填写PROJECT_URL将上传订阅,例如:https://merge.serv00.net
17
+ PROJECT_URL = os.environ.get('PROJECT_URL', '') # 项目url,需要自动保活或自动上传订阅需要填写,例如:https://www.google.com,
18
+ AUTO_ACCESS = os.environ.get('AUTO_ACCESS', 'false').lower() == 'true' # false关闭自动保活, true开启自动保活,默认关闭
19
+ FILE_PATH = os.environ.get('FILE_PATH', '/data/SillyTavern/public/') # 运行路径,sub.txt保存路径
20
+ SUB_PATH = os.environ.get('SUB_PATH', 'sub') # 订阅token,默认sub,例如:https://www.google.com/sub
21
+ UUID = os.environ.get('UUID', '20e6e496-cf19-45c8-b883-14f5e11cd9f1') # UUID,如使用哪吒v1,在不同的平台部署需要修改,否则会覆盖
22
+ NEZHA_SERVER = os.environ.get('NEZHA_SERVER', '') # 哪吒面板域名或ip, v1格式: nezha.xxx.com:8008, v0格式: nezha.xxx.com
23
+ NEZHA_PORT = os.environ.get('NEZHA_PORT', '443') # v1哪吒请留空, v0哪吒的agent通信端口,自动匹配tls
24
+ NEZHA_KEY = os.environ.get('NEZHA_KEY', '') # v1哪吒的NZ_CLIENT_SECRET或v0哪吒agent密钥
25
+ ARGO_DOMAIN = os.environ.get('ARGO_DOMAIN', 'hf-jg11.9.c.5.b.0.d.0.0.1.0.a.2.ip6.arpa') # Argo固定隧道域名,留空即使用临时隧道
26
+ ARGO_AUTH = os.environ.get('ARGO_AUTH', 'eyJhIjoiZWM1MTk5ZTYwZGYxYWI2YmM2OTdhMGYzMTAzYzY4NTUiLCJ0IjoiNWY4M2Q4MTMtY2M1MC00ZjU4LWE4NzctZjU4ZGQ5ZTRhZGJjIiwicyI6IlltTTNPVGhoTXpndE5HWXdOaTAwTXpVM0xXRmxZemt0WXpsallUQmtOemN6WmpJMiJ9') # Argo固定隧道密钥,留空即使用临时隧道
27
+ ARGO_PORT = int(os.environ.get('ARGO_PORT', '8001')) # Argo端口,使用固定隧道token需在cloudflare后台设置端口和这里一致
28
+ CFIP = os.environ.get('CFIP', 'cf.877774.xyz') # 优选ip或优选域名
29
+ CFPORT = int(os.environ.get('CFPORT', '443')) # 优选ip或优选域名对应端口
30
+ NAME = os.environ.get('NAME', '柒蓝-公益酒馆11号') # 节点名称
31
+ CHAT_ID = os.environ.get('CHAT_ID', '') # Telegram chat_id,推送节点到tg,两个变量同时填写才会推送
32
+ BOT_TOKEN = os.environ.get('BOT_TOKEN', '') # Telegram bot_token
33
+ PORT = int(os.environ.get('SERVER_PORT') or os.environ.get('PORT') or 3000) # 订阅端口,如无法订阅,请手动修改为分配的端口
34
+
35
+ # Create running folder
36
+ def create_directory():
37
+ print('\033c', end='')
38
+ if not os.path.exists(FILE_PATH):
39
+ os.makedirs(FILE_PATH)
40
+ print(f"{FILE_PATH} is created")
41
+ else:
42
+ print(f"{FILE_PATH} already exists")
43
+
44
+ # Global variables
45
+ npm_path = os.path.join(FILE_PATH, 'npm')
46
+ php_path = os.path.join(FILE_PATH, 'php')
47
+ web_path = os.path.join(FILE_PATH, 'web')
48
+ bot_path = os.path.join(FILE_PATH, 'bot')
49
+ sub_path = os.path.join(FILE_PATH, 'sub.txt')
50
+ list_path = os.path.join(FILE_PATH, 'list.txt')
51
+ boot_log_path = os.path.join(FILE_PATH, 'boot.log')
52
+ config_path = os.path.join(FILE_PATH, 'config.json')
53
+
54
+
55
+
56
+
57
+
58
+
59
+ # Delete nodes
60
+ def delete_nodes():
61
+ try:
62
+ if not UPLOAD_URL:
63
+ return
64
+
65
+ if not os.path.exists(sub_path):
66
+ return
67
+
68
+ try:
69
+ with open(sub_path, 'r') as file:
70
+ file_content = file.read()
71
+ except:
72
+ return None
73
+
74
+ decoded = base64.b64decode(file_content).decode('utf-8')
75
+ nodes = [line for line in decoded.split('\n') if any(protocol in line for protocol in ['vless://', 'vmess://', 'trojan://', 'hysteria2://', 'tuic://'])]
76
+
77
+ if not nodes:
78
+ return
79
+
80
+ try:
81
+ requests.post(f"{UPLOAD_URL}/api/delete-nodes",
82
+ data=json.dumps({"nodes": nodes}),
83
+ headers={"Content-Type": "application/json"})
84
+ except:
85
+ return None
86
+ except Exception as e:
87
+ print(f"Error in delete_nodes: {e}")
88
+ return None
89
+
90
+ # Clean up old files
91
+ def cleanup_old_files():
92
+ paths_to_delete = ['web', 'bot', 'npm', 'php', 'boot.log', 'list.txt']
93
+ for file in paths_to_delete:
94
+ file_path = os.path.join(FILE_PATH, file)
95
+ try:
96
+ if os.path.exists(file_path):
97
+ if os.path.isdir(file_path):
98
+ shutil.rmtree(file_path)
99
+ else:
100
+ os.remove(file_path)
101
+ except Exception as e:
102
+ print(f"Error removing {file_path}: {e}")
103
+
104
+ class RequestHandler(BaseHTTPRequestHandler):
105
+ def do_GET(self):
106
+ if self.path == '/':
107
+ self.send_response(200)
108
+ self.send_header('Content-type', 'text/html')
109
+ self.end_headers()
110
+ self.wfile.write(b'Hello World')
111
+
112
+ elif self.path == f'/{SUB_PATH}':
113
+ try:
114
+ with open(sub_path, 'rb') as f:
115
+ content = f.read()
116
+ self.send_response(200)
117
+ self.send_header('Content-type', 'text/plain')
118
+ self.end_headers()
119
+ self.wfile.write(content)
120
+ except:
121
+ self.send_response(404)
122
+ self.end_headers()
123
+ else:
124
+ self.send_response(404)
125
+ self.end_headers()
126
+
127
+ def log_message(self, format, *args):
128
+ pass
129
+
130
+ # Determine system architecture
131
+ def get_system_architecture():
132
+ architecture = platform.machine().lower()
133
+ if 'arm' in architecture or 'aarch64' in architecture:
134
+ return 'arm'
135
+ else:
136
+ return 'amd'
137
+
138
+ # Download file based on architecture
139
+ def download_file(file_name, file_url):
140
+ file_path = os.path.join(FILE_PATH, file_name)
141
+ try:
142
+ response = requests.get(file_url, stream=True)
143
+ response.raise_for_status()
144
+
145
+ with open(file_path, 'wb') as f:
146
+ for chunk in response.iter_content(chunk_size=8192):
147
+ f.write(chunk)
148
+
149
+ print(f"Download {file_name} successfully")
150
+ return True
151
+ except Exception as e:
152
+ if os.path.exists(file_path):
153
+ os.remove(file_path)
154
+ print(f"Download {file_name} failed: {e}")
155
+ return False
156
+
157
+ # Get files for architecture
158
+ def get_files_for_architecture(architecture):
159
+ if architecture == 'arm':
160
+ base_files = [
161
+ {"fileName": "web", "fileUrl": "https://arm64.ssss.nyc.mn/web"},
162
+ {"fileName": "bot", "fileUrl": "https://arm64.ssss.nyc.mn/2go"}
163
+ ]
164
+ else:
165
+ base_files = [
166
+ {"fileName": "web", "fileUrl": "https://amd64.ssss.nyc.mn/web"},
167
+ {"fileName": "bot", "fileUrl": "https://amd64.ssss.nyc.mn/2go"}
168
+ ]
169
+
170
+ if NEZHA_SERVER and NEZHA_KEY:
171
+ if NEZHA_PORT:
172
+ npm_url = "https://arm64.ssss.nyc.mn/agent" if architecture == 'arm' else "https://amd64.ssss.nyc.mn/agent"
173
+ base_files.insert(0, {"fileName": "npm", "fileUrl": npm_url})
174
+ else:
175
+ php_url = "https://arm64.ssss.nyc.mn/v1" if architecture == 'arm' else "https://amd64.ssss.nyc.mn/v1"
176
+ base_files.insert(0, {"fileName": "php", "fileUrl": php_url})
177
+
178
+ return base_files
179
+
180
+ # Authorize files with execute permission
181
+ def authorize_files(file_paths):
182
+ for relative_file_path in file_paths:
183
+ absolute_file_path = os.path.join(FILE_PATH, relative_file_path)
184
+ if os.path.exists(absolute_file_path):
185
+ try:
186
+ os.chmod(absolute_file_path, 0o775)
187
+ print(f"Empowerment success for {absolute_file_path}: 775")
188
+ except Exception as e:
189
+ print(f"Empowerment failed for {absolute_file_path}: {e}")
190
+
191
+ # Configure Argo tunnel
192
+ def argo_type():
193
+ if not ARGO_AUTH or not ARGO_DOMAIN:
194
+ print("ARGO_DOMAIN or ARGO_AUTH variable is empty, use quick tunnels")
195
+ return
196
+
197
+ if "TunnelSecret" in ARGO_AUTH:
198
+ with open(os.path.join(FILE_PATH, 'tunnel.json'), 'w') as f:
199
+ f.write(ARGO_AUTH)
200
+
201
+ tunnel_id = ARGO_AUTH.split('"')[11]
202
+ tunnel_yml = f"""
203
+ tunnel: {tunnel_id}
204
+ credentials-file: {os.path.join(FILE_PATH, 'tunnel.json')}
205
+ protocol: http2
206
+
207
+ ingress:
208
+ - hostname: {ARGO_DOMAIN}
209
+ service: http://localhost:{ARGO_PORT}
210
+ originRequest:
211
+ noTLSVerify: true
212
+ - service: http_status:404
213
+ """
214
+ with open(os.path.join(FILE_PATH, 'tunnel.yml'), 'w') as f:
215
+ f.write(tunnel_yml)
216
+ else:
217
+ print("Use token connect to tunnel,please set the {ARGO_PORT} in cloudflare")
218
+
219
+ # Execute shell command and return output
220
+ def exec_cmd(command):
221
+ try:
222
+ process = subprocess.Popen(
223
+ command,
224
+ shell=True,
225
+ stdout=subprocess.PIPE,
226
+ stderr=subprocess.PIPE,
227
+ text=True
228
+ )
229
+ stdout, stderr = process.communicate()
230
+ return stdout + stderr
231
+ except Exception as e:
232
+ print(f"Error executing command: {e}")
233
+ return str(e)
234
+
235
+ # Download and run necessary files
236
+ async def download_files_and_run():
237
+ global private_key, public_key
238
+
239
+ architecture = get_system_architecture()
240
+ files_to_download = get_files_for_architecture(architecture)
241
+
242
+ if not files_to_download:
243
+ print("Can't find a file for the current architecture")
244
+ return
245
+
246
+ # Download all files
247
+ download_success = True
248
+ for file_info in files_to_download:
249
+ if not download_file(file_info["fileName"], file_info["fileUrl"]):
250
+ download_success = False
251
+
252
+ if not download_success:
253
+ print("Error downloading files")
254
+ return
255
+
256
+ # Authorize files
257
+ files_to_authorize = ['npm', 'web', 'bot'] if NEZHA_PORT else ['php', 'web', 'bot']
258
+ authorize_files(files_to_authorize)
259
+
260
+ # Check TLS
261
+ port = NEZHA_SERVER.split(":")[-1] if ":" in NEZHA_SERVER else ""
262
+ if port in ["443", "8443", "2096", "2087", "2083", "2053"]:
263
+ nezha_tls = "true"
264
+ else:
265
+ nezha_tls = "false"
266
+
267
+ # Configure nezha
268
+ if NEZHA_SERVER and NEZHA_KEY:
269
+ if not NEZHA_PORT:
270
+ # Generate config.yaml for v1
271
+ config_yaml = f"""
272
+ client_secret: {NEZHA_KEY}
273
+ debug: false
274
+ disable_auto_update: true
275
+ disable_command_execute: false
276
+ disable_force_update: true
277
+ disable_nat: false
278
+ disable_send_query: false
279
+ gpu: false
280
+ insecure_tls: false
281
+ ip_report_period: 1800
282
+ report_delay: 4
283
+ server: {NEZHA_SERVER}
284
+ skip_connection_count: false
285
+ skip_procs_count: false
286
+ temperature: false
287
+ tls: {nezha_tls}
288
+ use_gitee_to_upgrade: false
289
+ use_ipv6_country_code: false
290
+ uuid: {UUID}"""
291
+
292
+ with open(os.path.join(FILE_PATH, 'config.yaml'), 'w') as f:
293
+ f.write(config_yaml)
294
+
295
+ # Generate configuration file
296
+ config ={"log":{"access":"/dev/null","error":"/dev/null","loglevel":"none",},"inbounds":[{"port":ARGO_PORT ,"protocol":"vless","settings":{"clients":[{"id":UUID ,"flow":"xtls-rprx-vision",},],"decryption":"none","fallbacks":[{"dest":3001 },{"path":"/vless-argo","dest":3002 },{"path":"/vmess-argo","dest":3003 },{"path":"/trojan-argo","dest":3004 },],},"streamSettings":{"network":"tcp",},},{"port":3001 ,"listen":"127.0.0.1","protocol":"vless","settings":{"clients":[{"id":UUID },],"decryption":"none"},"streamSettings":{"network":"ws","security":"none"}},{"port":3002 ,"listen":"127.0.0.1","protocol":"vless","settings":{"clients":[{"id":UUID ,"level":0 }],"decryption":"none"},"streamSettings":{"network":"ws","security":"none","wsSettings":{"path":"/vless-argo"}},"sniffing":{"enabled":True ,"destOverride":["http","tls","quic"],"metadataOnly":False }},{"port":3003 ,"listen":"127.0.0.1","protocol":"vmess","settings":{"clients":[{"id":UUID ,"alterId":0 }]},"streamSettings":{"network":"ws","wsSettings":{"path":"/vmess-argo"}},"sniffing":{"enabled":True ,"destOverride":["http","tls","quic"],"metadataOnly":False }},{"port":3004 ,"listen":"127.0.0.1","protocol":"trojan","settings":{"clients":[{"password":UUID },]},"streamSettings":{"network":"ws","security":"none","wsSettings":{"path":"/trojan-argo"}},"sniffing":{"enabled":True ,"destOverride":["http","tls","quic"],"metadataOnly":False }},],"outbounds":[{"protocol":"freedom","tag": "direct" },{"protocol":"blackhole","tag":"block"}]}
297
+
298
+ config1 = {
299
+ "log": {
300
+ "access": "/dev/null",
301
+ "error": "/dev/null",
302
+ "loglevel": "none"
303
+ },
304
+ "inbounds": [
305
+ {
306
+ "port": ARGO_PORT,
307
+ "protocol": "vless",
308
+ "settings": {
309
+ "clients": [{"id": UUID, "flow": "xtls-rprx-vision"}],
310
+ "decryption": "none",
311
+ "fallbacks": [
312
+ {"dest": 3001},
313
+ {"path": "/vless-argo", "dest": 3002},
314
+ {"path": "/vmess-argo", "dest": 3003},
315
+ {"path": "/trojan-argo", "dest": 3004}
316
+ ]
317
+ },
318
+ "streamSettings": {"network": "tcp"}
319
+ },
320
+ {
321
+ "port": 3001,
322
+ "listen": "127.0.0.1",
323
+ "protocol": "vless",
324
+ "settings": {
325
+ "clients": [{"id": UUID}],
326
+ "decryption": "none"
327
+ },
328
+ "streamSettings": {"network": "ws", "security": "none"}
329
+ },
330
+ {
331
+ "port": 3002,
332
+ "listen": "127.0.0.1",
333
+ "protocol": "vless",
334
+ "settings": {
335
+ "clients": [{"id": UUID, "level": 0}],
336
+ "decryption": "none"
337
+ },
338
+ "streamSettings": {
339
+ "network": "ws",
340
+ "security": "none",
341
+ "wsSettings": {"path": "/vless-argo"}
342
+ },
343
+ "sniffing": {
344
+ "enabled": True,
345
+ "destOverride": ["http", "tls", "quic"],
346
+ "metadataOnly": False
347
+ }
348
+ },
349
+ {
350
+ "port": 3003,
351
+ "listen": "127.0.0.1",
352
+ "protocol": "vmess",
353
+ "settings": {
354
+ "clients": [{"id": UUID, "alterId": 0}]
355
+ },
356
+ "streamSettings": {
357
+ "network": "ws",
358
+ "wsSettings": {"path": "/vmess-argo"}
359
+ },
360
+ "sniffing": {
361
+ "enabled": True,
362
+ "destOverride": ["http", "tls", "quic"],
363
+ "metadataOnly": False
364
+ }
365
+ },
366
+ {
367
+ "port": 3004,
368
+ "listen": "127.0.0.1",
369
+ "protocol": "trojan",
370
+ "settings": {
371
+ "clients": [{"password": UUID}]
372
+ },
373
+ "streamSettings": {
374
+ "network": "ws",
375
+ "security": "none",
376
+ "wsSettings": {"path": "/trojan-argo"}
377
+ },
378
+ "sniffing": {
379
+ "enabled": True,
380
+ "destOverride": ["http", "tls", "quic"],
381
+ "metadataOnly": False
382
+ }
383
+ }
384
+ ],
385
+ "outbounds": [
386
+ {"protocol": "freedom", "tag": "direct"},
387
+ {
388
+ "protocol": "vmess",
389
+ "tag": "youtube",
390
+ "settings": {
391
+ "vnext": [{
392
+ "address": "172.233.171.224",
393
+ "port": 16416,
394
+ "users": [{
395
+ "id": "8c1b9bea-cb51-43bb-a65c-0af31bbbf145",
396
+ "alterId": 0
397
+ }]
398
+ }]
399
+ },
400
+ "streamSettings": {"network": "tcp"}
401
+ },
402
+ {"protocol": "blackhole", "tag": "block"}
403
+ ],
404
+ "routing": {
405
+ "domainStrategy": "IPIfNonMatch",
406
+ "rules": [
407
+ {
408
+ "type": "field",
409
+ "domain": [
410
+ "youtube.com",
411
+ "youtu.be",
412
+ "googlevideo.com",
413
+ "ytimg.com",
414
+ "gstatic.com",
415
+ "googleapis.com",
416
+ "ggpht.com",
417
+ "googleusercontent.com"
418
+ ],
419
+ "outboundTag": "youtube"
420
+ }
421
+ ]
422
+ }
423
+ }
424
+ with open(os.path.join(FILE_PATH, 'config.json'), 'w', encoding='utf-8') as config_file:
425
+ json.dump(config, config_file, ensure_ascii=False, indent=2)
426
+
427
+ # Run nezha
428
+ if NEZHA_SERVER and NEZHA_PORT and NEZHA_KEY:
429
+ tls_ports = ['443', '8443', '2096', '2087', '2083', '2053']
430
+ nezha_tls = '--tls' if NEZHA_PORT in tls_ports else ''
431
+ command = f"nohup {os.path.join(FILE_PATH, 'npm')} -s {NEZHA_SERVER}:{NEZHA_PORT} -p {NEZHA_KEY} {nezha_tls} >/dev/null 2>&1 &"
432
+
433
+ try:
434
+ exec_cmd(command)
435
+ print('npm is running')
436
+ time.sleep(1)
437
+ except Exception as e:
438
+ print(f"npm running error: {e}")
439
+
440
+ elif NEZHA_SERVER and NEZHA_KEY:
441
+ # Run V1
442
+ command = f"nohup {FILE_PATH}/php -c \"{FILE_PATH}/config.yaml\" >/dev/null 2>&1 &"
443
+ try:
444
+ exec_cmd(command)
445
+ print('php is running')
446
+ time.sleep(1)
447
+ except Exception as e:
448
+ print(f"php running error: {e}")
449
+ else:
450
+ print('NEZHA variable is empty, skipping running')
451
+
452
+ # Run sbX
453
+ command = f"nohup {os.path.join(FILE_PATH, 'web')} -c {os.path.join(FILE_PATH, 'config.json')} >/dev/null 2>&1 &"
454
+ try:
455
+ exec_cmd(command)
456
+ print('web is running')
457
+ time.sleep(1)
458
+ except Exception as e:
459
+ print(f"web running error: {e}")
460
+
461
+ # Run cloudflared
462
+ if os.path.exists(os.path.join(FILE_PATH, 'bot')):
463
+ if re.match(r'^[A-Z0-9a-z=]{120,250}$', ARGO_AUTH):
464
+ args = f"tunnel --edge-ip-version auto --no-autoupdate --protocol http2 run --token {ARGO_AUTH}"
465
+ elif "TunnelSecret" in ARGO_AUTH:
466
+ args = f"tunnel --edge-ip-version auto --config {os.path.join(FILE_PATH, 'tunnel.yml')} run"
467
+ else:
468
+ args = f"tunnel --edge-ip-version auto --no-autoupdate --protocol http2 --logfile {os.path.join(FILE_PATH, 'boot.log')} --loglevel info --url http://localhost:{ARGO_PORT}"
469
+
470
+ try:
471
+ exec_cmd(f"nohup {os.path.join(FILE_PATH, 'bot')} {args} >/dev/null 2>&1 &")
472
+ print('bot is running')
473
+ time.sleep(2)
474
+ except Exception as e:
475
+ print(f"Error executing command: {e}")
476
+
477
+ time.sleep(5)
478
+
479
+ # Extract domains and generate sub.txt
480
+ await extract_domains()
481
+
482
+ # Extract domains from cloudflared logs
483
+ async def extract_domains():
484
+ argo_domain = None
485
+
486
+ if ARGO_AUTH and ARGO_DOMAIN:
487
+ argo_domain = ARGO_DOMAIN
488
+ print(f'ARGO_DOMAIN: {argo_domain}')
489
+ await generate_links(argo_domain)
490
+ else:
491
+ try:
492
+ with open(boot_log_path, 'r') as f:
493
+ file_content = f.read()
494
+
495
+ lines = file_content.split('\n')
496
+ argo_domains = []
497
+
498
+ for line in lines:
499
+ domain_match = re.search(r'https?://([^ ]*trycloudflare\.com)/?', line)
500
+ if domain_match:
501
+ domain = domain_match.group(1)
502
+ argo_domains.append(domain)
503
+
504
+ if argo_domains:
505
+ argo_domain = argo_domains[0]
506
+ print(f'ArgoDomain: {argo_domain}')
507
+ await generate_links(argo_domain)
508
+ else:
509
+ print('ArgoDomain not found, re-running bot to obtain ArgoDomain')
510
+ # Remove boot.log and restart bot
511
+ if os.path.exists(boot_log_path):
512
+ os.remove(boot_log_path)
513
+
514
+ try:
515
+ exec_cmd('pkill -f "[b]ot" > /dev/null 2>&1')
516
+ except:
517
+ pass
518
+
519
+ time.sleep(1)
520
+ args = f'tunnel --edge-ip-version auto --no-autoupdate --protocol http2 --logfile {FILE_PATH}/boot.log --loglevel info --url http://localhost:{ARGO_PORT}'
521
+ exec_cmd(f'nohup {os.path.join(FILE_PATH, "bot")} {args} >/dev/null 2>&1 &')
522
+ print('bot is running.')
523
+ time.sleep(6) # Wait 6 seconds
524
+ await extract_domains() # Try again
525
+ except Exception as e:
526
+ print(f'Error reading boot.log: {e}')
527
+
528
+ # Upload nodes to subscription service
529
+ def upload_nodes():
530
+ if UPLOAD_URL and PROJECT_URL:
531
+ subscription_url = f"{PROJECT_URL}/{SUB_PATH}"
532
+ json_data = {
533
+ "subscription": [subscription_url]
534
+ }
535
+
536
+ try:
537
+ response = requests.post(
538
+ f"{UPLOAD_URL}/api/add-subscriptions",
539
+ json=json_data,
540
+ headers={"Content-Type": "application/json"}
541
+ )
542
+
543
+ if response.status_code == 200:
544
+ print('Subscription uploaded successfully')
545
+ except Exception as e:
546
+ pass
547
+
548
+ elif UPLOAD_URL:
549
+ if not os.path.exists(list_path):
550
+ return
551
+
552
+ with open(list_path, 'r') as f:
553
+ content = f.read()
554
+
555
+ nodes = [line for line in content.split('\n') if any(protocol in line for protocol in ['vless://', 'vmess://', 'trojan://', 'hysteria2://', 'tuic://'])]
556
+
557
+ if not nodes:
558
+ return
559
+
560
+ json_data = json.dumps({"nodes": nodes})
561
+
562
+ try:
563
+ response = requests.post(
564
+ f"{UPLOAD_URL}/api/add-nodes",
565
+ data=json_data,
566
+ headers={"Content-Type": "application/json"}
567
+ )
568
+
569
+ if response.status_code == 200:
570
+ print('Nodes uploaded successfully')
571
+ except:
572
+ return None
573
+ else:
574
+ return
575
+
576
+ # Send notification to Telegram
577
+ def send_telegram():
578
+ if not BOT_TOKEN or not CHAT_ID:
579
+ # print('TG variables is empty, Skipping push nodes to TG')
580
+ return
581
+
582
+ try:
583
+ with open(sub_path, 'r') as f:
584
+ message = f.read()
585
+
586
+ url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
587
+
588
+ escaped_name = re.sub(r'([_*\[\]()~>#+=|{}.!\-])', r'\\\1', NAME)
589
+
590
+ params = {
591
+ "chat_id": CHAT_ID,
592
+ "text": f"**{escaped_name}节点推送通知**\n{message}",
593
+ "parse_mode": "MarkdownV2"
594
+ }
595
+
596
+ requests.post(url, params=params)
597
+ print('Telegram message sent successfully')
598
+ except Exception as e:
599
+ print(f'Failed to send Telegram message: {e}')
600
+
601
+ # Generate links and subscription content
602
+ async def generate_links(argo_domain):
603
+ meta_info = subprocess.run(['curl', '-s', 'https://speed.cloudflare.com/meta'], capture_output=True, text=True)
604
+ meta_info = meta_info.stdout.split('"')
605
+ ISP = f"{meta_info[25]}-{meta_info[17]}".replace(' ', '_').strip()
606
+
607
+ time.sleep(2)
608
+ VMESS = {"v": "2", "ps": f"{NAME}", "add": 'time.is', "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
609
+ VMESS2 = {"v": "2", "ps": f"{NAME}", "add": 'cf.877774.xyz', "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
610
+ VMESS3 = {"v": "2", "ps": f"{NAME}", "add": 'nrtcfdns.zone.id', "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
611
+ VMESS4 = {"v": "2", "ps": f"{NAME}", "add": 'dogechain.info', "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
612
+ VMESS5 = {"v": "2", "ps": f"{NAME}", "add": 'ip.sb', "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
613
+ VMESS6 = {"v": "2", "ps": f"{NAME}", "add": '104.19.37.4', "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
614
+ VMESS7 = {"v": "2", "ps": f"{NAME}", "add": 'linux.do', "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
615
+ VMESS8 = {"v": "2", "ps": f"{NAME}", "add": 'www.visa.com.tw', "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
616
+ VMESS9 = {"v": "2", "ps": f"{NAME}", "add": 'cf.090227.xyz', "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
617
+ VMESS10 = {"v": "2", "ps": f"{NAME}", "add": 'freeyx.cloudflare88.eu.org', "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
618
+ VMESS11 = {"v": "2", "ps": f"{NAME}", "add": 'cloudflare.cdnjson.com', "port": CFPORT, "id": UUID, "aid": "0", "scy": "none", "net": "ws", "type": "none", "host": argo_domain, "path": "/vmess-argo?ed=2560", "tls": "tls", "sni": argo_domain, "alpn": "", "fp": "chrome"}
619
+
620
+ list_txt = f"""
621
+ vless://{UUID}@time.is:{CFPORT}?encryption=none&security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Fvless-argo%3Fed%3D2560#{NAME}
622
+ vmess://{ base64.b64encode(json.dumps(VMESS).encode('utf-8')).decode('utf-8')}
623
+ trojan://{UUID}@time.is:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
624
+
625
+ vless://{UUID}@cf.877774.xyz:{CFPORT}?encryption=none&security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Fvless-argo%3Fed%3D2560#{NAME}
626
+ vmess://{ base64.b64encode(json.dumps(VMESS2).encode('utf-8')).decode('utf-8')}
627
+ trojan://{UUID}@cf.877774.xyz:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
628
+
629
+ vless://{UUID}@nrtcfdns.zone.id:{CFPORT}?encryption=none&security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Fvless-argo%3Fed%3D2560#{NAME}
630
+ vmess://{ base64.b64encode(json.dumps(VMESS3).encode('utf-8')).decode('utf-8')}
631
+ trojan://{UUID}@nrtcfdns.zone.id:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
632
+
633
+ vless://{UUID}@ip.sb:{CFPORT}?encryption=none&security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Fvless-argo%3Fed%3D2560#{NAME}
634
+ vmess://{ base64.b64encode(json.dumps(VMESS5).encode('utf-8')).decode('utf-8')}
635
+ trojan://{UUID}@ip.sb:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
636
+
637
+ vless://{UUID}@104.19.37.4:{CFPORT}?encryption=none&security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Fvless-argo%3Fed%3D2560#{NAME}
638
+ vmess://{ base64.b64encode(json.dumps(VMESS6).encode('utf-8')).decode('utf-8')}
639
+ trojan://{UUID}@104.19.37.4:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
640
+
641
+ vless://{UUID}@linux.do:{CFPORT}?encryption=none&security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Fvless-argo%3Fed%3D2560#{NAME}
642
+ vmess://{ base64.b64encode(json.dumps(VMESS7).encode('utf-8')).decode('utf-8')}
643
+ trojan://{UUID}@linux.do:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
644
+
645
+ vless://{UUID}@www.visa.com.tw:{CFPORT}?encryption=none&security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Fvless-argo%3Fed%3D2560#{NAME}
646
+ vmess://{ base64.b64encode(json.dumps(VMESS8).encode('utf-8')).decode('utf-8')}
647
+ trojan://{UUID}@www.visa.com.tw:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
648
+
649
+ vless://{UUID}@cf.090227.xyz:{CFPORT}?encryption=none&security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Fvless-argo%3Fed%3D2560#{NAME}
650
+ vmess://{ base64.b64encode(json.dumps(VMESS9).encode('utf-8')).decode('utf-8')}
651
+ trojan://{UUID}@cf.090227.xyz:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
652
+
653
+ vless://{UUID}@freeyx.cloudflare88.eu.org:{CFPORT}?encryption=none&security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Fvless-argo%3Fed%3D2560#{NAME}
654
+ vmess://{ base64.b64encode(json.dumps(VMESS10).encode('utf-8')).decode('utf-8')}
655
+ trojan://{UUID}@freeyx.cloudflare88.eu.org:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
656
+
657
+ vless://{UUID}@cloudflare.cdnjson.com:{CFPORT}?encryption=none&security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Fvless-argo%3Fed%3D2560#{NAME}
658
+ vmess://{ base64.b64encode(json.dumps(VMESS11).encode('utf-8')).decode('utf-8')}
659
+ trojan://{UUID}@cloudflare.cdnjson.com:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
660
+ """
661
+
662
+ with open(os.path.join(FILE_PATH, 'list.txt'), 'w', encoding='utf-8') as list_file:
663
+ list_file.write(list_txt)
664
+
665
+ sub_txt = base64.b64encode(list_txt.encode('utf-8')).decode('utf-8')
666
+ with open(os.path.join(FILE_PATH, 'sub.txt'), 'w', encoding='utf-8') as sub_file:
667
+ sub_file.write(sub_txt)
668
+
669
+ print(sub_txt)
670
+
671
+ print(f"{FILE_PATH}/sub.txt saved successfully")
672
+
673
+ # Additional actions
674
+ send_telegram()
675
+ upload_nodes()
676
+
677
+ return sub_txt
678
+
679
+ # Add automatic access task
680
+ def add_visit_task():
681
+ if not AUTO_ACCESS or not PROJECT_URL:
682
+ print("Skipping adding automatic access task")
683
+ return
684
+
685
+ try:
686
+ response = requests.post(
687
+ 'https://keep.gvrander.eu.org/add-url',
688
+ json={"url": PROJECT_URL},
689
+ headers={"Content-Type": "application/json"}
690
+ )
691
+ print('automatic access task added successfully')
692
+ except Exception as e:
693
+ print(f'Failed to add URL: {e}')
694
+
695
+ # Clean up files after 90 seconds
696
+ def clean_files():
697
+ def _cleanup():
698
+ time.sleep(90) # Wait 90 seconds
699
+ files_to_delete = [boot_log_path, config_path, list_path, web_path, bot_path, php_path, npm_path]
700
+
701
+ if NEZHA_PORT:
702
+ files_to_delete.append(npm_path)
703
+ elif NEZHA_SERVER and NEZHA_KEY:
704
+ files_to_delete.append(php_path)
705
+
706
+ for file in files_to_delete:
707
+ try:
708
+ if os.path.exists(file):
709
+ if os.path.isdir(file):
710
+ shutil.rmtree(file)
711
+ else:
712
+ os.remove(file)
713
+ except:
714
+ pass
715
+
716
+ print('\033c', end='')
717
+ print('App is running')
718
+ print('Thank you for using this script, enjoy!')
719
+
720
+ threading.Thread(target=_cleanup, daemon=True).start()
721
+
722
+ import psutil
723
+ import os
724
+ import signal
725
+
726
+ def find_and_kill_cf_processes():
727
+ # 查找包含 'cf' 的进程
728
+ cf_processes = []
729
+
730
+ for proc in psutil.process_iter(['name', 'cmdline']):
731
+ try:
732
+ # 检查进程名或命令行中是否包含 'cf'
733
+ if 'cf' in proc.info['name'].lower() or \
734
+ any('cf' in str(cmd).lower() for cmd in proc.info['cmdline'] or []):
735
+ cf_processes.append(proc)
736
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
737
+ pass
738
+
739
+ # 杀掉找到的进程
740
+ for proc in cf_processes:
741
+ try:
742
+ print(f"Killing process: PID {proc.pid}, Name: {proc.info['name']}")
743
+ # 先尝试正常终止
744
+ proc.terminate()
745
+
746
+ # 等待一段时间
747
+ try:
748
+ proc.wait(timeout=3)
749
+ except psutil.TimeoutExpired:
750
+ # 如果无法正常终止,强制杀掉
751
+ print(f"Force killing process: PID {proc.pid}")
752
+ proc.kill()
753
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
754
+ pass
755
+
756
+ print(f"Total CF processes killed: {len(cf_processes)}")
757
+
758
+ # 运行函数
759
+
760
+
761
+
762
+
763
+ # Main function to start the server
764
+ async def start_server():
765
+ delete_nodes()
766
+ cleanup_old_files()
767
+ create_directory()
768
+ argo_type()
769
+ await download_files_and_run()
770
+ add_visit_task()
771
+
772
+ server_thread = Thread(target=run_server)
773
+ server_thread.daemon = True
774
+ server_thread.start()
775
+
776
+ clean_files()
777
+
778
+ def run_server():
779
+ server = HTTPServer(('0.0.0.0', PORT), RequestHandler)
780
+ print(f"Server is running on port {PORT}")
781
+ print(f"Running done!")
782
+ print(f"\nLogs will be delete in 90 seconds")
783
+ # find_and_kill_cf_processes()
784
+ # os.system("wget -O /data/cf 'https://github.com/cloudflare/cloudflared/releases/download/2025.8.1/cloudflared-linux-amd64' && chmod +x /data/cf")
785
+ # # os.system("/data/cf tunnel run --token eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiOGViMjIyMTItNWY1YS00ZWRkLWI1YTUtOGU4NmFmOWI0ZjNiIiwicyI6Ik4yWmtPR1JpWkdFdFpETTNOeTAwTXpVNExXRm1Zek10T0RRME16WmlNRE5oWW1RMyJ9")
786
+ # # 使用subprocess.Popen()可以异步执行命令
787
+ # process = subprocess.Popen(["/data/cf", "tunnel", "run", "--token", "eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiOGViMjIyMTItNWY1YS00ZWRkLWI1YTUtOGU4NmFmOWI0ZjNiIiwicyI6Ik4yWmtPR1JpWkdFdFpETTNOeTAwTXpVNExXRm1Zek10T0RRME16WmlNRE5oWW1RMyJ9"],
788
+ # stdout=subprocess.PIPE,
789
+ # stderr=subprocess.PIPE)
790
+ # 后续代码会立即继续执行
791
+
792
+ os.system("pwd")
793
+ server.serve_forever()
794
+
795
+ def run_async():
796
+ loop = asyncio.new_event_loop()
797
+ asyncio.set_event_loop(loop)
798
+ loop.run_until_complete(start_server())
799
+
800
+ while True:
801
+ time.sleep(3600)
802
+
803
+ if __name__ == "__main__":
804
+ run_async()