Qilan2 commited on
Commit
80027d4
·
verified ·
1 Parent(s): dbf65d9

Create app1.py

Browse files
Files changed (1) hide show
  1. sbx/a/app1.py +808 -0
sbx/a/app1.py ADDED
@@ -0,0 +1,808 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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') # 运行路径,sub.txt保存路径
20
+ SUB_PATH = os.environ.get('SUB_PATH', 'sub') # 订阅token,默认sub,例如:https://www.google.com/sub
21
+ UUID = os.environ.get('UUID', '94784a68-3ef8-4403-bad6-4031a9c8d4cb') # UUID,如使用哪吒v1,在不同的平台部署需要修改,否则会覆盖
22
+ NEZHA_SERVER = os.environ.get('NEZHA_SERVER', 'z.282820.xyz:443') # 哪吒面板域名或ip, v1格式: nezha.xxx.com:8008, v0格式: nezha.xxx.com
23
+ NEZHA_PORT = os.environ.get('NEZHA_PORT', '') # v1哪吒请留空, v0哪吒的agent通信端口,自动匹配tls
24
+ NEZHA_KEY = os.environ.get('NEZHA_KEY', 'MLcD6YnifhoY08B9n129UP5cg2139NYa') # v1哪吒的NZ_CLIENT_SECRET或v0哪吒agent密钥
25
+ ARGO_DOMAIN = os.environ.get('ARGO_DOMAIN', 'hf-baosa-us.2.2.a.a.f.f.0.7.0.0.6.2.ip6.arpa') # Argo固定隧道域名,留空即使用临时隧道
26
+ ARGO_AUTH = os.environ.get('ARGO_AUTH', 'eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiOGYwOWVhNGQtYWJjMy00NzBlLTlkNWEtODcyOWZjMzFiNDI4IiwicyI6IllXUTRaRFZtWWpRdFlXWmxNeTAwWWpSbUxXSmpaRGd0TmpNME1qVXhOakEyWmpZdyJ9') # 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', '抱脸-美国') # 节点名称
31
+ CHAT_ID = os.environ.get('CHAT_ID', '-4829459058') # Telegram chat_id,推送节点到tg,两个变量同时填写才会推送
32
+ BOT_TOKEN = os.environ.get('BOT_TOKEN', '8259739796:AAGZY4tboUxJ3jnMi1GTpGtV3_-Tf2rMT7I') # 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
+ config = {
298
+ "log": {
299
+ "access": "/dev/null",
300
+ "error": "/dev/null",
301
+ "loglevel": "none"
302
+ },
303
+ "inbounds": [
304
+ {
305
+ "port": ARGO_PORT,
306
+ "protocol": "vless",
307
+ "settings": {
308
+ "clients": [{"id": UUID, "flow": "xtls-rprx-vision"}],
309
+ "decryption": "none",
310
+ "fallbacks": [
311
+ {"dest": 3001},
312
+ {"path": "/vless-argo", "dest": 3002},
313
+ {"path": "/vmess-argo", "dest": 3003},
314
+ {"path": "/trojan-argo", "dest": 3004}
315
+ ]
316
+ },
317
+ "streamSettings": {"network": "tcp"}
318
+ },
319
+ {
320
+ "port": 3001,
321
+ "listen": "127.0.0.1",
322
+ "protocol": "vless",
323
+ "settings": {
324
+ "clients": [{"id": UUID}],
325
+ "decryption": "none"
326
+ },
327
+ "streamSettings": {"network": "ws", "security": "none"}
328
+ },
329
+ {
330
+ "port": 3002,
331
+ "listen": "127.0.0.1",
332
+ "protocol": "vless",
333
+ "settings": {
334
+ "clients": [{"id": UUID, "level": 0}],
335
+ "decryption": "none"
336
+ },
337
+ "streamSettings": {
338
+ "network": "ws",
339
+ "security": "none",
340
+ "wsSettings": {"path": "/vless-argo"}
341
+ },
342
+ "sniffing": {
343
+ "enabled": True,
344
+ "destOverride": ["http", "tls", "quic"],
345
+ "metadataOnly": False
346
+ }
347
+ },
348
+ {
349
+ "port": 3003,
350
+ "listen": "127.0.0.1",
351
+ "protocol": "vmess",
352
+ "settings": {
353
+ "clients": [{"id": UUID, "alterId": 0}]
354
+ },
355
+ "streamSettings": {
356
+ "network": "ws",
357
+ "wsSettings": {"path": "/vmess-argo"}
358
+ },
359
+ "sniffing": {
360
+ "enabled": True,
361
+ "destOverride": ["http", "tls", "quic"],
362
+ "metadataOnly": False
363
+ }
364
+ },
365
+ {
366
+ "port": 3004,
367
+ "listen": "127.0.0.1",
368
+ "protocol": "trojan",
369
+ "settings": {
370
+ "clients": [{"password": UUID}]
371
+ },
372
+ "streamSettings": {
373
+ "network": "ws",
374
+ "security": "none",
375
+ "wsSettings": {"path": "/trojan-argo"}
376
+ },
377
+ "sniffing": {
378
+ "enabled": True,
379
+ "destOverride": ["http", "tls", "quic"],
380
+ "metadataOnly": False
381
+ }
382
+ }
383
+ ],
384
+ "outbounds": [
385
+ {"protocol": "freedom", "tag": "direct"},
386
+ {
387
+ "protocol": "vmess",
388
+ "tag": "youtube",
389
+ "settings": {
390
+ "vnext": [{
391
+ "address": "172.233.171.224",
392
+ "port": 16416,
393
+ "users": [{
394
+ "id": "8c1b9bea-cb51-43bb-a65c-0af31bbbf145",
395
+ "alterId": 0
396
+ }]
397
+ }]
398
+ },
399
+ "streamSettings": {"network": "tcp"}
400
+ },
401
+ {"protocol": "blackhole", "tag": "block"}
402
+ ],
403
+ "routing": {
404
+ "domainStrategy": "IPIfNonMatch",
405
+ "rules": [
406
+ {
407
+ "type": "field",
408
+ "domain": [
409
+ "*.youtube.com",
410
+ "studio.youtube.com",
411
+ "music.youtube.com",
412
+ "github.com",
413
+ "www.youtube.com",
414
+ "youtube.com",
415
+ "youtu.be",
416
+ "googlevideo.com",
417
+ "ytimg.com",
418
+ "gstatic.com",
419
+ "googleapis.com",
420
+ "ggpht.com",
421
+ "googleusercontent.com"
422
+ ],
423
+ "outboundTag": "youtube"
424
+ }
425
+ ]
426
+ }
427
+ }
428
+ with open(os.path.join(FILE_PATH, 'config.json'), 'w', encoding='utf-8') as config_file:
429
+ json.dump(config, config_file, ensure_ascii=False, indent=2)
430
+
431
+ # Run nezha
432
+ if NEZHA_SERVER and NEZHA_PORT and NEZHA_KEY:
433
+ tls_ports = ['443', '8443', '2096', '2087', '2083', '2053']
434
+ nezha_tls = '--tls' if NEZHA_PORT in tls_ports else ''
435
+ command = f"nohup {os.path.join(FILE_PATH, 'npm')} -s {NEZHA_SERVER}:{NEZHA_PORT} -p {NEZHA_KEY} {nezha_tls} >/dev/null 2>&1 &"
436
+
437
+ try:
438
+ exec_cmd(command)
439
+ print('npm is running')
440
+ time.sleep(1)
441
+ except Exception as e:
442
+ print(f"npm running error: {e}")
443
+
444
+ elif NEZHA_SERVER and NEZHA_KEY:
445
+ # Run V1
446
+ command = f"nohup {FILE_PATH}/php -c \"{FILE_PATH}/config.yaml\" >/dev/null 2>&1 &"
447
+ try:
448
+ exec_cmd(command)
449
+ print('php is running')
450
+ time.sleep(1)
451
+ except Exception as e:
452
+ print(f"php running error: {e}")
453
+ else:
454
+ print('NEZHA variable is empty, skipping running')
455
+
456
+ # Run sbX
457
+ command = f"nohup {os.path.join(FILE_PATH, 'web')} -c {os.path.join(FILE_PATH, 'config.json')} >/dev/null 2>&1 &"
458
+ try:
459
+ exec_cmd(command)
460
+ print('web is running')
461
+ time.sleep(1)
462
+ except Exception as e:
463
+ print(f"web running error: {e}")
464
+
465
+ # Run cloudflared
466
+ if os.path.exists(os.path.join(FILE_PATH, 'bot')):
467
+ if re.match(r'^[A-Z0-9a-z=]{120,250}$', ARGO_AUTH):
468
+ args = f"tunnel --edge-ip-version auto --no-autoupdate --protocol http2 run --token {ARGO_AUTH}"
469
+ elif "TunnelSecret" in ARGO_AUTH:
470
+ args = f"tunnel --edge-ip-version auto --config {os.path.join(FILE_PATH, 'tunnel.yml')} run"
471
+ else:
472
+ 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}"
473
+
474
+ try:
475
+ exec_cmd(f"nohup {os.path.join(FILE_PATH, 'bot')} {args} >/dev/null 2>&1 &")
476
+ print('bot is running')
477
+ time.sleep(2)
478
+ except Exception as e:
479
+ print(f"Error executing command: {e}")
480
+
481
+ time.sleep(5)
482
+
483
+ # Extract domains and generate sub.txt
484
+ await extract_domains()
485
+
486
+ # Extract domains from cloudflared logs
487
+ async def extract_domains():
488
+ argo_domain = None
489
+
490
+ if ARGO_AUTH and ARGO_DOMAIN:
491
+ argo_domain = ARGO_DOMAIN
492
+ print(f'ARGO_DOMAIN: {argo_domain}')
493
+ await generate_links(argo_domain)
494
+ else:
495
+ try:
496
+ with open(boot_log_path, 'r') as f:
497
+ file_content = f.read()
498
+
499
+ lines = file_content.split('\n')
500
+ argo_domains = []
501
+
502
+ for line in lines:
503
+ domain_match = re.search(r'https?://([^ ]*trycloudflare\.com)/?', line)
504
+ if domain_match:
505
+ domain = domain_match.group(1)
506
+ argo_domains.append(domain)
507
+
508
+ if argo_domains:
509
+ argo_domain = argo_domains[0]
510
+ print(f'ArgoDomain: {argo_domain}')
511
+ await generate_links(argo_domain)
512
+ else:
513
+ print('ArgoDomain not found, re-running bot to obtain ArgoDomain')
514
+ # Remove boot.log and restart bot
515
+ if os.path.exists(boot_log_path):
516
+ os.remove(boot_log_path)
517
+
518
+ try:
519
+ exec_cmd('pkill -f "[b]ot" > /dev/null 2>&1')
520
+ except:
521
+ pass
522
+
523
+ time.sleep(1)
524
+ args = f'tunnel --edge-ip-version auto --no-autoupdate --protocol http2 --logfile {FILE_PATH}/boot.log --loglevel info --url http://localhost:{ARGO_PORT}'
525
+ exec_cmd(f'nohup {os.path.join(FILE_PATH, "bot")} {args} >/dev/null 2>&1 &')
526
+ print('bot is running.')
527
+ time.sleep(6) # Wait 6 seconds
528
+ await extract_domains() # Try again
529
+ except Exception as e:
530
+ print(f'Error reading boot.log: {e}')
531
+
532
+ # Upload nodes to subscription service
533
+ def upload_nodes():
534
+ if UPLOAD_URL and PROJECT_URL:
535
+ subscription_url = f"{PROJECT_URL}/{SUB_PATH}"
536
+ json_data = {
537
+ "subscription": [subscription_url]
538
+ }
539
+
540
+ try:
541
+ response = requests.post(
542
+ f"{UPLOAD_URL}/api/add-subscriptions",
543
+ json=json_data,
544
+ headers={"Content-Type": "application/json"}
545
+ )
546
+
547
+ if response.status_code == 200:
548
+ print('Subscription uploaded successfully')
549
+ except Exception as e:
550
+ pass
551
+
552
+ elif UPLOAD_URL:
553
+ if not os.path.exists(list_path):
554
+ return
555
+
556
+ with open(list_path, 'r') as f:
557
+ content = f.read()
558
+
559
+ nodes = [line for line in content.split('\n') if any(protocol in line for protocol in ['vless://', 'vmess://', 'trojan://', 'hysteria2://', 'tuic://'])]
560
+
561
+ if not nodes:
562
+ return
563
+
564
+ json_data = json.dumps({"nodes": nodes})
565
+
566
+ try:
567
+ response = requests.post(
568
+ f"{UPLOAD_URL}/api/add-nodes",
569
+ data=json_data,
570
+ headers={"Content-Type": "application/json"}
571
+ )
572
+
573
+ if response.status_code == 200:
574
+ print('Nodes uploaded successfully')
575
+ except:
576
+ return None
577
+ else:
578
+ return
579
+
580
+ # Send notification to Telegram
581
+ def send_telegram():
582
+ if not BOT_TOKEN or not CHAT_ID:
583
+ # print('TG variables is empty, Skipping push nodes to TG')
584
+ return
585
+
586
+ try:
587
+ with open(sub_path, 'r') as f:
588
+ message = f.read()
589
+
590
+ url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
591
+
592
+ escaped_name = re.sub(r'([_*\[\]()~>#+=|{}.!\-])', r'\\\1', NAME)
593
+
594
+ params = {
595
+ "chat_id": CHAT_ID,
596
+ "text": f"**{escaped_name}节点推送通知**\n{message}",
597
+ "parse_mode": "MarkdownV2"
598
+ }
599
+
600
+ requests.post(url, params=params)
601
+ print('Telegram message sent successfully')
602
+ except Exception as e:
603
+ print(f'Failed to send Telegram message: {e}')
604
+
605
+ # Generate links and subscription content
606
+ async def generate_links(argo_domain):
607
+ meta_info = subprocess.run(['curl', '-s', 'https://speed.cloudflare.com/meta'], capture_output=True, text=True)
608
+ meta_info = meta_info.stdout.split('"')
609
+ ISP = f"{meta_info[25]}-{meta_info[17]}".replace(' ', '_').strip()
610
+
611
+ time.sleep(2)
612
+ 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"}
613
+ 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"}
614
+ 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"}
615
+ 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"}
616
+ 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"}
617
+ 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"}
618
+ 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"}
619
+ 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"}
620
+ 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"}
621
+ 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"}
622
+ 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"}
623
+
624
+ list_txt = f"""
625
+ 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}
626
+ vmess://{ base64.b64encode(json.dumps(VMESS).encode('utf-8')).decode('utf-8')}
627
+ trojan://{UUID}@time.is:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
628
+
629
+ 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}
630
+ vmess://{ base64.b64encode(json.dumps(VMESS2).encode('utf-8')).decode('utf-8')}
631
+ trojan://{UUID}@cf.877774.xyz:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
632
+
633
+ 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}
634
+ vmess://{ base64.b64encode(json.dumps(VMESS3).encode('utf-8')).decode('utf-8')}
635
+ trojan://{UUID}@nrtcfdns.zone.id:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
636
+
637
+ 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}
638
+ vmess://{ base64.b64encode(json.dumps(VMESS5).encode('utf-8')).decode('utf-8')}
639
+ trojan://{UUID}@ip.sb:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
640
+
641
+ 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}
642
+ vmess://{ base64.b64encode(json.dumps(VMESS6).encode('utf-8')).decode('utf-8')}
643
+ 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}
644
+
645
+ 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}
646
+ vmess://{ base64.b64encode(json.dumps(VMESS7).encode('utf-8')).decode('utf-8')}
647
+ trojan://{UUID}@linux.do:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
648
+
649
+ 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}
650
+ vmess://{ base64.b64encode(json.dumps(VMESS8).encode('utf-8')).decode('utf-8')}
651
+ 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}
652
+
653
+ 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}
654
+ vmess://{ base64.b64encode(json.dumps(VMESS9).encode('utf-8')).decode('utf-8')}
655
+ trojan://{UUID}@cf.090227.xyz:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
656
+
657
+ 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}
658
+ vmess://{ base64.b64encode(json.dumps(VMESS10).encode('utf-8')).decode('utf-8')}
659
+ 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}
660
+
661
+ 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}
662
+ vmess://{ base64.b64encode(json.dumps(VMESS11).encode('utf-8')).decode('utf-8')}
663
+ trojan://{UUID}@cloudflare.cdnjson.com:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}
664
+ """
665
+
666
+ with open(os.path.join(FILE_PATH, 'list.txt'), 'w', encoding='utf-8') as list_file:
667
+ list_file.write(list_txt)
668
+
669
+ sub_txt = base64.b64encode(list_txt.encode('utf-8')).decode('utf-8')
670
+ with open(os.path.join(FILE_PATH, 'sub.txt'), 'w', encoding='utf-8') as sub_file:
671
+ sub_file.write(sub_txt)
672
+
673
+ print(sub_txt)
674
+
675
+ print(f"{FILE_PATH}/sub.txt saved successfully")
676
+
677
+ # Additional actions
678
+ send_telegram()
679
+ upload_nodes()
680
+
681
+ return sub_txt
682
+
683
+ # Add automatic access task
684
+ def add_visit_task():
685
+ if not AUTO_ACCESS or not PROJECT_URL:
686
+ print("Skipping adding automatic access task")
687
+ return
688
+
689
+ try:
690
+ response = requests.post(
691
+ 'https://keep.gvrander.eu.org/add-url',
692
+ json={"url": PROJECT_URL},
693
+ headers={"Content-Type": "application/json"}
694
+ )
695
+ print('automatic access task added successfully')
696
+ except Exception as e:
697
+ print(f'Failed to add URL: {e}')
698
+
699
+ # Clean up files after 90 seconds
700
+ def clean_files():
701
+ def _cleanup():
702
+ time.sleep(90) # Wait 90 seconds
703
+ files_to_delete = [boot_log_path, config_path, list_path, web_path, bot_path, php_path, npm_path]
704
+
705
+ if NEZHA_PORT:
706
+ files_to_delete.append(npm_path)
707
+ elif NEZHA_SERVER and NEZHA_KEY:
708
+ files_to_delete.append(php_path)
709
+
710
+ for file in files_to_delete:
711
+ try:
712
+ if os.path.exists(file):
713
+ if os.path.isdir(file):
714
+ shutil.rmtree(file)
715
+ else:
716
+ os.remove(file)
717
+ except:
718
+ pass
719
+
720
+ print('\033c', end='')
721
+ print('App is running')
722
+ print('Thank you for using this script, enjoy!')
723
+
724
+ threading.Thread(target=_cleanup, daemon=True).start()
725
+
726
+ import psutil
727
+ import os
728
+ import signal
729
+
730
+ def find_and_kill_cf_processes():
731
+ # 查找包含 'cf' 的进程
732
+ cf_processes = []
733
+
734
+ for proc in psutil.process_iter(['name', 'cmdline']):
735
+ try:
736
+ # 检查进程名或命令行中是否包含 'cf'
737
+ if 'cf' in proc.info['name'].lower() or \
738
+ any('cf' in str(cmd).lower() for cmd in proc.info['cmdline'] or []):
739
+ cf_processes.append(proc)
740
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
741
+ pass
742
+
743
+ # 杀掉找到的进程
744
+ for proc in cf_processes:
745
+ try:
746
+ print(f"Killing process: PID {proc.pid}, Name: {proc.info['name']}")
747
+ # 先尝试正常终止
748
+ proc.terminate()
749
+
750
+ # 等待一段时间
751
+ try:
752
+ proc.wait(timeout=3)
753
+ except psutil.TimeoutExpired:
754
+ # 如果无法正常终止,强制杀掉
755
+ print(f"Force killing process: PID {proc.pid}")
756
+ proc.kill()
757
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
758
+ pass
759
+
760
+ print(f"Total CF processes killed: {len(cf_processes)}")
761
+
762
+ # 运行函数
763
+
764
+
765
+
766
+
767
+ # Main function to start the server
768
+ async def start_server():
769
+ delete_nodes()
770
+ cleanup_old_files()
771
+ create_directory()
772
+ argo_type()
773
+ await download_files_and_run()
774
+ add_visit_task()
775
+
776
+ server_thread = Thread(target=run_server)
777
+ server_thread.daemon = True
778
+ server_thread.start()
779
+
780
+ clean_files()
781
+
782
+ def run_server():
783
+ server = HTTPServer(('0.0.0.0', PORT), RequestHandler)
784
+ print(f"Server is running on port {PORT}")
785
+ print(f"Running done!")
786
+ print(f"\nLogs will be delete in 90 seconds")
787
+ # find_and_kill_cf_processes()
788
+ # os.system("wget -O /data/cf 'https://github.com/cloudflare/cloudflared/releases/download/2025.8.1/cloudflared-linux-amd64' && chmod +x /data/cf")
789
+ # # os.system("/data/cf tunnel run --token eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiOGViMjIyMTItNWY1YS00ZWRkLWI1YTUtOGU4NmFmOWI0ZjNiIiwicyI6Ik4yWmtPR1JpWkdFdFpETTNOeTAwTXpVNExXRm1Zek10T0RRME16WmlNRE5oWW1RMyJ9")
790
+ # # 使用subprocess.Popen()可以异步执行命令
791
+ # process = subprocess.Popen(["/data/cf", "tunnel", "run", "--token", "eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiOGViMjIyMTItNWY1YS00ZWRkLWI1YTUtOGU4NmFmOWI0ZjNiIiwicyI6Ik4yWmtPR1JpWkdFdFpETTNOeTAwTXpVNExXRm1Zek10T0RRME16WmlNRE5oWW1RMyJ9"],
792
+ # stdout=subprocess.PIPE,
793
+ # stderr=subprocess.PIPE)
794
+ # 后续��码会立即继续执行
795
+
796
+ os.system("pwd")
797
+ server.serve_forever()
798
+
799
+ def run_async():
800
+ loop = asyncio.new_event_loop()
801
+ asyncio.set_event_loop(loop)
802
+ loop.run_until_complete(start_server())
803
+
804
+ while True:
805
+ time.sleep(3600)
806
+
807
+ if __name__ == "__main__":
808
+ run_async()