Qilan2 commited on
Commit
76e4e2c
·
verified ·
1 Parent(s): 870488f

Upload 4 files

Browse files
Files changed (4) hide show
  1. sbx/a/Dockerfile +85 -0
  2. sbx/a/app.py +652 -0
  3. sbx/a/c.py +61 -0
  4. sbx/a/start_server.sh +5 -0
sbx/a/Dockerfile ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM alpine:latest
2
+ RUN pwd
3
+
4
+ # 安装必要依赖
5
+ RUN apk update && \
6
+ apk add --no-cache \
7
+ ca-certificates \
8
+ curl \
9
+ wget \
10
+ bzip2 \
11
+ p7zip \
12
+ pigz \
13
+ pv \
14
+ git \
15
+ sudo \
16
+ python3 \
17
+ python3-dev \
18
+ py3-pip \
19
+ build-base \
20
+ linux-headers \
21
+ gcc \
22
+ musl-dev \
23
+ libffi-dev \
24
+ openssl-dev \
25
+ nodejs \
26
+ npm \
27
+ bash \
28
+ py3-requests \
29
+ py3-flask \
30
+ py3-pexpect \
31
+ py3-psutil
32
+
33
+ # 创建必要的目录并设置权限
34
+ RUN mkdir -p /tmp/app /tmp/app/frp /.kaggle /data /root/.kaggle && \
35
+ chmod -R 777 /tmp/app /tmp/app/frp /.kaggle /data /root/.kaggle
36
+
37
+ # 设置工作目录
38
+ WORKDIR /data
39
+
40
+ # 创建虚拟环境并安装 Python 包
41
+ RUN python3 -m venv /opt/venv && \
42
+ . /opt/venv/bin/activate && \
43
+ pip install --upgrade pip && \
44
+ pip install --no-cache-dir \
45
+ jupyterlab \
46
+ notebook \
47
+ pexpect \
48
+ psutil \
49
+ requests \
50
+ pytz \
51
+ flask \
52
+ kaggle \
53
+ ipykernel
54
+
55
+ # 安装 configurable-http-proxy
56
+ RUN npm install -g configurable-http-proxy
57
+
58
+ # 配置 sudo
59
+ RUN echo "root ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers && \
60
+ chmod 0440 /etc/sudoers
61
+
62
+ # 设置环境变量
63
+ ENV JUPYTER_RUNTIME_DIR=/tmp/app/runtime
64
+ ENV JUPYTER_DATA_DIR=/tmp/app/data
65
+ ENV HOME=/tmp/app
66
+ ENV PATH="/opt/venv/bin:$PATH"
67
+
68
+ # 创建运行时目录
69
+ RUN mkdir -p /tmp/app/runtime && \
70
+ chmod 777 /tmp/app/runtime
71
+
72
+ # 暴露端口
73
+ EXPOSE 7860
74
+
75
+
76
+ CMD ["/tmp/app/start_server.sh"]
77
+ # 启动 Jupyterlab
78
+ CMD ["jupyter", "lab", \
79
+ "--ip=0.0.0.0", \
80
+ "--port=7860", \
81
+ "--no-browser", \
82
+ "--allow-root", \
83
+ "--notebook-dir=/data", \
84
+ "--NotebookApp.token='qilan'", \
85
+ "--ServerApp.disable_check_xsrf=True"]
sbx/a/app.py ADDED
@@ -0,0 +1,652 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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', '20e6e496-cf19-45c8-b883-14f5e11cd9f1') # UUID,如使用哪吒v1,在不同的平台部署需要修改,否则会覆盖
22
+ NEZHA_SERVER = os.environ.get('NEZHA_SERVER', 'tzz.282820.xyz') # 哪吒面板域名或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', 'AaAEbuhxGa5IA24v0J') # 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
+ with open(os.path.join(FILE_PATH, 'config.json'), 'w', encoding='utf-8') as config_file:
298
+ json.dump(config, config_file, ensure_ascii=False, indent=2)
299
+
300
+ # Run nezha
301
+ if NEZHA_SERVER and NEZHA_PORT and NEZHA_KEY:
302
+ tls_ports = ['443', '8443', '2096', '2087', '2083', '2053']
303
+ nezha_tls = '--tls' if NEZHA_PORT in tls_ports else ''
304
+ command = f"nohup {os.path.join(FILE_PATH, 'npm')} -s {NEZHA_SERVER}:{NEZHA_PORT} -p {NEZHA_KEY} {nezha_tls} >/dev/null 2>&1 &"
305
+
306
+ try:
307
+ exec_cmd(command)
308
+ print('npm is running')
309
+ time.sleep(1)
310
+ except Exception as e:
311
+ print(f"npm running error: {e}")
312
+
313
+ elif NEZHA_SERVER and NEZHA_KEY:
314
+ # Run V1
315
+ command = f"nohup {FILE_PATH}/php -c \"{FILE_PATH}/config.yaml\" >/dev/null 2>&1 &"
316
+ try:
317
+ exec_cmd(command)
318
+ print('php is running')
319
+ time.sleep(1)
320
+ except Exception as e:
321
+ print(f"php running error: {e}")
322
+ else:
323
+ print('NEZHA variable is empty, skipping running')
324
+
325
+ # Run sbX
326
+ command = f"nohup {os.path.join(FILE_PATH, 'web')} -c {os.path.join(FILE_PATH, 'config.json')} >/dev/null 2>&1 &"
327
+ try:
328
+ exec_cmd(command)
329
+ print('web is running')
330
+ time.sleep(1)
331
+ except Exception as e:
332
+ print(f"web running error: {e}")
333
+
334
+ # Run cloudflared
335
+ if os.path.exists(os.path.join(FILE_PATH, 'bot')):
336
+ if re.match(r'^[A-Z0-9a-z=]{120,250}$', ARGO_AUTH):
337
+ args = f"tunnel --edge-ip-version auto --no-autoupdate --protocol http2 run --token {ARGO_AUTH}"
338
+ elif "TunnelSecret" in ARGO_AUTH:
339
+ args = f"tunnel --edge-ip-version auto --config {os.path.join(FILE_PATH, 'tunnel.yml')} run"
340
+ else:
341
+ 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}"
342
+
343
+ try:
344
+ exec_cmd(f"nohup {os.path.join(FILE_PATH, 'bot')} {args} >/dev/null 2>&1 &")
345
+ print('bot is running')
346
+ time.sleep(2)
347
+ except Exception as e:
348
+ print(f"Error executing command: {e}")
349
+
350
+ time.sleep(5)
351
+
352
+ # Extract domains and generate sub.txt
353
+ await extract_domains()
354
+
355
+ # Extract domains from cloudflared logs
356
+ async def extract_domains():
357
+ argo_domain = None
358
+
359
+ if ARGO_AUTH and ARGO_DOMAIN:
360
+ argo_domain = ARGO_DOMAIN
361
+ print(f'ARGO_DOMAIN: {argo_domain}')
362
+ await generate_links(argo_domain)
363
+ else:
364
+ try:
365
+ with open(boot_log_path, 'r') as f:
366
+ file_content = f.read()
367
+
368
+ lines = file_content.split('\n')
369
+ argo_domains = []
370
+
371
+ for line in lines:
372
+ domain_match = re.search(r'https?://([^ ]*trycloudflare\.com)/?', line)
373
+ if domain_match:
374
+ domain = domain_match.group(1)
375
+ argo_domains.append(domain)
376
+
377
+ if argo_domains:
378
+ argo_domain = argo_domains[0]
379
+ print(f'ArgoDomain: {argo_domain}')
380
+ await generate_links(argo_domain)
381
+ else:
382
+ print('ArgoDomain not found, re-running bot to obtain ArgoDomain')
383
+ # Remove boot.log and restart bot
384
+ if os.path.exists(boot_log_path):
385
+ os.remove(boot_log_path)
386
+
387
+ try:
388
+ exec_cmd('pkill -f "[b]ot" > /dev/null 2>&1')
389
+ except:
390
+ pass
391
+
392
+ time.sleep(1)
393
+ args = f'tunnel --edge-ip-version auto --no-autoupdate --protocol http2 --logfile {FILE_PATH}/boot.log --loglevel info --url http://localhost:{ARGO_PORT}'
394
+ exec_cmd(f'nohup {os.path.join(FILE_PATH, "bot")} {args} >/dev/null 2>&1 &')
395
+ print('bot is running.')
396
+ time.sleep(6) # Wait 6 seconds
397
+ await extract_domains() # Try again
398
+ except Exception as e:
399
+ print(f'Error reading boot.log: {e}')
400
+
401
+ # Upload nodes to subscription service
402
+ def upload_nodes():
403
+ if UPLOAD_URL and PROJECT_URL:
404
+ subscription_url = f"{PROJECT_URL}/{SUB_PATH}"
405
+ json_data = {
406
+ "subscription": [subscription_url]
407
+ }
408
+
409
+ try:
410
+ response = requests.post(
411
+ f"{UPLOAD_URL}/api/add-subscriptions",
412
+ json=json_data,
413
+ headers={"Content-Type": "application/json"}
414
+ )
415
+
416
+ if response.status_code == 200:
417
+ print('Subscription uploaded successfully')
418
+ except Exception as e:
419
+ pass
420
+
421
+ elif UPLOAD_URL:
422
+ if not os.path.exists(list_path):
423
+ return
424
+
425
+ with open(list_path, 'r') as f:
426
+ content = f.read()
427
+
428
+ nodes = [line for line in content.split('\n') if any(protocol in line for protocol in ['vless://', 'vmess://', 'trojan://', 'hysteria2://', 'tuic://'])]
429
+
430
+ if not nodes:
431
+ return
432
+
433
+ json_data = json.dumps({"nodes": nodes})
434
+
435
+ try:
436
+ response = requests.post(
437
+ f"{UPLOAD_URL}/api/add-nodes",
438
+ data=json_data,
439
+ headers={"Content-Type": "application/json"}
440
+ )
441
+
442
+ if response.status_code == 200:
443
+ print('Nodes uploaded successfully')
444
+ except:
445
+ return None
446
+ else:
447
+ return
448
+
449
+ # Send notification to Telegram
450
+ def send_telegram():
451
+ if not BOT_TOKEN or not CHAT_ID:
452
+ # print('TG variables is empty, Skipping push nodes to TG')
453
+ return
454
+
455
+ try:
456
+ with open(sub_path, 'r') as f:
457
+ message = f.read()
458
+
459
+ url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
460
+
461
+ escaped_name = re.sub(r'([_*\[\]()~>#+=|{}.!\-])', r'\\\1', NAME)
462
+
463
+ params = {
464
+ "chat_id": CHAT_ID,
465
+ "text": f"**{escaped_name}节点推送通知**\n{message}",
466
+ "parse_mode": "MarkdownV2"
467
+ }
468
+
469
+ requests.post(url, params=params)
470
+ print('Telegram message sent successfully')
471
+ except Exception as e:
472
+ print(f'Failed to send Telegram message: {e}')
473
+
474
+ # Generate links and subscription content
475
+ async def generate_links(argo_domain):
476
+ meta_info = subprocess.run(['curl', '-s', 'https://speed.cloudflare.com/meta'], capture_output=True, text=True)
477
+ meta_info = meta_info.stdout.split('"')
478
+ ISP = f"{meta_info[25]}-{meta_info[17]}".replace(' ', '_').strip()
479
+
480
+ time.sleep(2)
481
+ VMESS = {"v": "2", "ps": f"{NAME}-{ISP}", "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"}
482
+ VMESS2 = {"v": "2", "ps": f"{NAME}-{ISP}", "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"}
483
+ VMESS3 = {"v": "2", "ps": f"{NAME}-{ISP}", "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"}
484
+ VMESS4 = {"v": "2", "ps": f"{NAME}-{ISP}", "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"}
485
+ VMESS5 = {"v": "2", "ps": f"{NAME}-{ISP}", "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"}
486
+ VMESS6 = {"v": "2", "ps": f"{NAME}-{ISP}", "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"}
487
+
488
+ list_txt = f"""
489
+ 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}-{ISP}
490
+ vmess://{ base64.b64encode(json.dumps(VMESS).encode('utf-8')).decode('utf-8')}
491
+ trojan://{UUID}@time.is:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}-{ISP}
492
+
493
+ 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}-{ISP}
494
+ vmess://{ base64.b64encode(json.dumps(VMESS2).encode('utf-8')).decode('utf-8')}
495
+ trojan://{UUID}@cf.877774.xyz:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}-{ISP}
496
+
497
+ 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}-{ISP}
498
+ vmess://{ base64.b64encode(json.dumps(VMESS3).encode('utf-8')).decode('utf-8')}
499
+ trojan://{UUID}@nrtcfdns.zone.id:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}-{ISP}
500
+
501
+ 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}-{ISP}
502
+ vmess://{ base64.b64encode(json.dumps(VMESS5).encode('utf-8')).decode('utf-8')}
503
+ trojan://{UUID}@ip.sb:{CFPORT}?security=tls&sni={argo_domain}&fp=chrome&type=ws&host={argo_domain}&path=%2Ftrojan-argo%3Fed%3D2560#{NAME}-{ISP}
504
+
505
+ 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}-{ISP}
506
+ vmess://{ base64.b64encode(json.dumps(VMESS6).encode('utf-8')).decode('utf-8')}
507
+ 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}-{ISP}
508
+ """
509
+
510
+ with open(os.path.join(FILE_PATH, 'list.txt'), 'w', encoding='utf-8') as list_file:
511
+ list_file.write(list_txt)
512
+
513
+ sub_txt = base64.b64encode(list_txt.encode('utf-8')).decode('utf-8')
514
+ with open(os.path.join(FILE_PATH, 'sub.txt'), 'w', encoding='utf-8') as sub_file:
515
+ sub_file.write(sub_txt)
516
+
517
+ print(sub_txt)
518
+
519
+ print(f"{FILE_PATH}/sub.txt saved successfully")
520
+
521
+ # Additional actions
522
+ send_telegram()
523
+ upload_nodes()
524
+
525
+ return sub_txt
526
+
527
+ # Add automatic access task
528
+ def add_visit_task():
529
+ if not AUTO_ACCESS or not PROJECT_URL:
530
+ print("Skipping adding automatic access task")
531
+ return
532
+
533
+ try:
534
+ response = requests.post(
535
+ 'https://keep.gvrander.eu.org/add-url',
536
+ json={"url": PROJECT_URL},
537
+ headers={"Content-Type": "application/json"}
538
+ )
539
+ print('automatic access task added successfully')
540
+ except Exception as e:
541
+ print(f'Failed to add URL: {e}')
542
+
543
+ # Clean up files after 90 seconds
544
+ def clean_files():
545
+ def _cleanup():
546
+ time.sleep(90) # Wait 90 seconds
547
+ files_to_delete = [boot_log_path, config_path, list_path, web_path, bot_path, php_path, npm_path]
548
+
549
+ if NEZHA_PORT:
550
+ files_to_delete.append(npm_path)
551
+ elif NEZHA_SERVER and NEZHA_KEY:
552
+ files_to_delete.append(php_path)
553
+
554
+ for file in files_to_delete:
555
+ try:
556
+ if os.path.exists(file):
557
+ if os.path.isdir(file):
558
+ shutil.rmtree(file)
559
+ else:
560
+ os.remove(file)
561
+ except:
562
+ pass
563
+
564
+ print('\033c', end='')
565
+ print('App is running')
566
+ print('Thank you for using this script, enjoy!')
567
+
568
+ threading.Thread(target=_cleanup, daemon=True).start()
569
+
570
+ import psutil
571
+ import os
572
+ import signal
573
+
574
+ def find_and_kill_cf_processes():
575
+ # 查找包含 'cf' 的进程
576
+ cf_processes = []
577
+
578
+ for proc in psutil.process_iter(['name', 'cmdline']):
579
+ try:
580
+ # 检查进程名或命令行中是否包含 'cf'
581
+ if 'cf' in proc.info['name'].lower() or \
582
+ any('cf' in str(cmd).lower() for cmd in proc.info['cmdline'] or []):
583
+ cf_processes.append(proc)
584
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
585
+ pass
586
+
587
+ # 杀掉找到的进程
588
+ for proc in cf_processes:
589
+ try:
590
+ print(f"Killing process: PID {proc.pid}, Name: {proc.info['name']}")
591
+ # 先尝试正常终止
592
+ proc.terminate()
593
+
594
+ # 等待一段时间
595
+ try:
596
+ proc.wait(timeout=3)
597
+ except psutil.TimeoutExpired:
598
+ # 如果无法正常终止,强制杀掉
599
+ print(f"Force killing process: PID {proc.pid}")
600
+ proc.kill()
601
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
602
+ pass
603
+
604
+ print(f"Total CF processes killed: {len(cf_processes)}")
605
+
606
+ # 运行函数
607
+
608
+
609
+
610
+
611
+ # Main function to start the server
612
+ async def start_server():
613
+ delete_nodes()
614
+ cleanup_old_files()
615
+ create_directory()
616
+ argo_type()
617
+ await download_files_and_run()
618
+ add_visit_task()
619
+
620
+ server_thread = Thread(target=run_server)
621
+ server_thread.daemon = True
622
+ server_thread.start()
623
+
624
+ clean_files()
625
+
626
+ def run_server():
627
+ server = HTTPServer(('0.0.0.0', PORT), RequestHandler)
628
+ print(f"Server is running on port {PORT}")
629
+ print(f"Running done!")
630
+ print(f"\nLogs will be delete in 90 seconds")
631
+ # find_and_kill_cf_processes()
632
+ # os.system("wget -O /data/cf 'https://github.com/cloudflare/cloudflared/releases/download/2025.8.1/cloudflared-linux-amd64' && chmod +x /data/cf")
633
+ # # os.system("/data/cf tunnel run --token eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiOGViMjIyMTItNWY1YS00ZWRkLWI1YTUtOGU4NmFmOWI0ZjNiIiwicyI6Ik4yWmtPR1JpWkdFdFpETTNOeTAwTXpVNExXRm1Zek10T0RRME16WmlNRE5oWW1RMyJ9")
634
+ # # 使用subprocess.Popen()可以异步执行命令
635
+ # process = subprocess.Popen(["/data/cf", "tunnel", "run", "--token", "eyJhIjoiNmVjNWE5NzEzOGIzMTg4YTU2Y2U1NjdmMWRhZDBhMTUiLCJ0IjoiOGViMjIyMTItNWY1YS00ZWRkLWI1YTUtOGU4NmFmOWI0ZjNiIiwicyI6Ik4yWmtPR1JpWkdFdFpETTNOeTAwTXpVNExXRm1Zek10T0RRME16WmlNRE5oWW1RMyJ9"],
636
+ # stdout=subprocess.PIPE,
637
+ # stderr=subprocess.PIPE)
638
+ # 后续代码会立即继续执行
639
+
640
+ os.system("pwd")
641
+ server.serve_forever()
642
+
643
+ def run_async():
644
+ loop = asyncio.new_event_loop()
645
+ asyncio.set_event_loop(loop)
646
+ loop.run_until_complete(start_server())
647
+
648
+ while True:
649
+ time.sleep(3600)
650
+
651
+ if __name__ == "__main__":
652
+ run_async()
sbx/a/c.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import pytz
3
+ import time
4
+
5
+ while True:
6
+
7
+ # 检查是否是中国时区早上6点
8
+ china_tz = pytz.timezone('Asia/Shanghai')
9
+ now = datetime.now(china_tz)
10
+ if now.hour == 6 and now.minute < 2: # 6:00-6:05之间退出
11
+ print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 到达早上6点,退出循环")
12
+ break
13
+ else:
14
+ print(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}, 未到达早上6点")
15
+ time.sleep(5)
16
+ import requests
17
+
18
+ def _reconstruct_token(partial_token):
19
+ """
20
+ 重构完整的 token
21
+
22
+ :param partial_token: 部分 token
23
+ :return: 完整的 token
24
+ """
25
+ return partial_token.replace(" ", "")
26
+
27
+ def restart_huggingface_space(space_name, space_id, partial_token):
28
+ """
29
+ 重启 Hugging Face Space
30
+
31
+ :param space_name: Space 的命名空间
32
+ :param space_id: Space 的 ID
33
+ :param partial_token: Hugging Face 部分访问令牌
34
+ :return: 响应结果字典
35
+ """
36
+ # 重构完整 token
37
+ token = _reconstruct_token(partial_token)
38
+
39
+ url = f"https://huggingface.co/api/spaces/{space_name}/{space_id}/restart?factory=true"
40
+ headers = {
41
+ "Content-Type": "application/json",
42
+ "Authorization": f"Bearer {token}",
43
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
44
+ }
45
+
46
+ try:
47
+ response = requests.post(url, headers=headers, json={})
48
+ return {
49
+ "status_code": response.status_code,
50
+ "success": response.status_code == 200,
51
+ "message": response.text
52
+ }
53
+ except requests.RequestException as e:
54
+ return {
55
+ "status_code": None,
56
+ "success": False,
57
+ "message": str(e)
58
+ }
59
+
60
+ # 使用示例
61
+ result = restart_huggingface_space("baosa", "sx1", "hf_mFcVa DHkDGFFpsfsJXblWOFRCibAFWqAbW")
sbx/a/start_server.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ nohup python /tmp/app/app.py > /data/app.py.log 2>&1 &
3
+ nohup python /tmp/app/c.py > /data/c.py.log 2>&1 &
4
+
5
+ jupyter lab --ip=0.0.0.0 --port=7860 --no-browser --allow-root --notebook-dir=/data --NotebookApp.token='qilan' --ServerApp.disable_check_xsrf=True