Qilan2 commited on
Commit
d4dc587
·
verified ·
1 Parent(s): 1977348

Create server3.py

Browse files
Files changed (1) hide show
  1. server3.py +544 -0
server3.py ADDED
@@ -0,0 +1,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ini_content = {"username":"xovale7506","key":"502e30bafc004c02aa668a279df23f3e"}
2
+ frp_url = '8.219.240.86'
3
+ ssh_port = '7074'
4
+ st_url = f'http://{frp_url}:7073'
5
+ config_data = f"""
6
+ [common]
7
+ server_addr = {frp_url}
8
+ server_port = 7000
9
+
10
+ [safgha22]
11
+ type = tcp
12
+ local_ip = 127.0.0.1
13
+ local_port = 8000
14
+ remote_port = 7073
15
+ [safabf22]
16
+ type = tcp
17
+ local_ip = 127.0.0.1
18
+ local_port = 22
19
+ remote_port = {ssh_port}
20
+ [saffg22]
21
+ type = tcp
22
+ local_ip = 127.0.0.1
23
+ local_port = 3000
24
+ remote_port = 7075
25
+ """
26
+ config_data2 = """
27
+ [common]
28
+ server_addr = 120.26.228.135
29
+ server_port = 7000
30
+
31
+ [safghac22]
32
+ type = tcp
33
+ local_ip = 127.0.0.1
34
+ local_port = 8000
35
+ remote_port = 7073
36
+ """
37
+
38
+ kaggle_metadata = {
39
+ "title": "Your Dataset Title",
40
+ "id": "xovale7506/sillytavern2-data",
41
+ "licenses": [{"name": "CC0-1.0"}]
42
+ }
43
+ st_status = True
44
+ import subprocess
45
+ import os
46
+ import sys
47
+ from IPython.display import clear_output
48
+ import urllib.request
49
+ from pathlib import Path
50
+ import requests
51
+ import json
52
+ import threading
53
+ import time
54
+ import pexpect
55
+ import glob # 导入 glob 模块
56
+ from requests.adapters import HTTPAdapter
57
+ from requests.packages.urllib3.util.retry import Retry
58
+
59
+ os.system("export LC_ALL=zh_CN.UTF-8")
60
+ # 更新软件包列表
61
+ def update():
62
+ print('-----------更新软件包列表开始-------------')
63
+ os.system("sudo apt update")
64
+ # 安装 Node.js 和 npm
65
+ os.system("sudo apt install nodejs npm -y")
66
+ # 全局安装 forever
67
+ os.system("sudo npm install -g forever")
68
+ # 安装 p7zip-full
69
+ os.system("sudo apt install p7zip-full -y")
70
+ os.system("pip install -U kaggle")
71
+ os.system("apt-get install inotify-tools")
72
+ os.system("pip install ruamel.yaml") # install ruamel.yaml to solve the import issue
73
+ os.system("pip install pexpect")
74
+ print('-----------更新软件包列表结束-------------')
75
+ update()
76
+ from ruamel.yaml import YAML
77
+ clear_output(wait=True) # 清除输出
78
+
79
+ def kill_frpc_processes():
80
+ try:
81
+ # 使用pkill命令结束所有frpc进程
82
+ subprocess.run(['pkill', '-f', 'frpc'], check=True)
83
+ print("所有frpc进程已被结束。")
84
+ except subprocess.CalledProcessError as e:
85
+ # 如果pkill命令失败,打印错误信息
86
+ print(f"结束frpc进程时出错: {e}")
87
+ kill_frpc_processes()
88
+
89
+
90
+ # Oneapi中转
91
+ def Oneapi():
92
+ print('-----------Oneapi中转开始-------------')
93
+ # 删除旧的 one-api 文件夹(如果存在)
94
+ os.system("rm -rf /one/one-api") # 使用 -f 参数以避免错误
95
+ os.system("mkdir -p /one") # 创建目录
96
+ # 下载 one-api 文件
97
+ url = "https://github.com/songquanpeng/one-api/releases/download/v0.6.8/one-api"
98
+ os.system(f"wget {url} -O /one/one-api") # 正确下载并重命名为 /one/one-api
99
+ # 修改文件权限,使其可执行
100
+ os.system("chmod +x /one/one-api")
101
+ # 设置环境变量
102
+ os.environ["THEME"] = "berry"
103
+ os.environ["TIKTOKEN_CACHE_DIR"] = os.getcwd() # 使用Python的os.getcwd()获取当前工作目录
104
+ # 设置MySQL数据库的环境变量
105
+ db_user = "oneapi"
106
+ db_password = "epBjK5ZKysCe6yr3"
107
+ db_host = "106.52.51.116"
108
+ db_port = "3306"
109
+ db_name = "oneapi"
110
+ dsn = f"{db_user}:{db_password}@tcp({db_host}:{db_port})/{db_name}"
111
+ os.environ["SQL_DSN"] = dsn
112
+ command = ['/one/one-api', '--port', '3000']
113
+ process = subprocess.Popen(command) # 启动程序并将其放到后台执行
114
+ print(f"OneAPI程序已在后台启动,进程ID为:{process.pid}")
115
+ print('-----------Oneapi中转结束-------------')
116
+ # Oneapi()
117
+
118
+ # SSH
119
+ def run_command(command):
120
+ try:
121
+ subprocess.run(command, check=True, shell=True)
122
+ except subprocess.CalledProcessError as e:
123
+ print(f"An error occurred: {e}")
124
+ def ssh():
125
+ print('-----------SSH开始-------------')
126
+ subprocess.run("apt update", check=True, shell=True)
127
+ subprocess.run("apt install openssh-server -y", check=True, shell=True)
128
+ subprocess.run("apt-get install vim -y", check=True, shell=True)
129
+
130
+ config_client_cmd = "sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config"
131
+ subprocess.run(config_client_cmd, check=True, shell=True)
132
+ config_server_cmd = "sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config"
133
+ subprocess.run(config_server_cmd, check=True, shell=True)
134
+ run_command("systemctl restart ssh")
135
+
136
+ os.system("/etc/init.d/ssh restart")
137
+ os.system("echo 'root:qilan' | sudo chpasswd")
138
+ os.system("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
139
+ os.system("service ssh restart ")
140
+ os.system("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
141
+ print('-----------SSH结束-------------')
142
+ ssh()
143
+ clear_output()
144
+
145
+ import json
146
+ import os
147
+ import subprocess
148
+ import threading
149
+ import time
150
+
151
+ # 创建一个锁
152
+ lock = threading.Lock()
153
+ data_folder = '/sillytavern/*'
154
+ zip_file_path = '/a/sillytavern.zip'
155
+ metadata_file_path = '/a/dataset-metadata.json'
156
+ last_uploaded_size = -1
157
+
158
+ def update_last_uploaded_size(size):
159
+ global last_uploaded_size
160
+ last_uploaded_size = size
161
+
162
+
163
+
164
+ def compress_folder():
165
+ global last_uploaded_size # 声明使用全局变量
166
+
167
+ # 清理并创建目录 /a
168
+ if os.path.exists('/a'):
169
+ subprocess.run(['rm', '-r', '/a'])
170
+
171
+ os.makedirs('/a', exist_ok=True)
172
+
173
+ with lock: # 使用锁
174
+ if os.path.exists(zip_file_path):
175
+ print(f"压缩文件 {zip_file_path} 已存在,跳过本次压缩。")
176
+ return
177
+
178
+ print('开始压缩数据')
179
+ result = subprocess.run(['7z', 'a', '-tzip', '-mx=1','-mmt=2', zip_file_path, data_folder])
180
+ # 7z a -tzip -mx=1 -mmt=2 /a/sillytavern.zip /sillytavern/*
181
+ print('重命名压缩后的文件')
182
+ file_path = '/a/sillytavern.zip1'
183
+ subprocess.run(['mv', zip_file_path,file_path])
184
+ if result.returncode != 0:
185
+ print("压缩失败,请检查7z命令是否正确")
186
+ return
187
+
188
+ print(f"Data compressed into {file_path}")
189
+
190
+ file_size = os.path.getsize(file_path) # 获取压缩包的大小
191
+ print('文件大小:', file_size, '上次文件大小:', last_uploaded_size,file_size * 1024 ** 2)
192
+
193
+ # 判断是否大于800MB (800MB = 800 * 1024 * 1024 字节)
194
+ if file_size < (800 * 1024 ** 2):
195
+ print("文件小于800MB,不进行上传。")
196
+ return
197
+
198
+ if last_uploaded_size == -1 or file_size > last_uploaded_size:
199
+ # 判断是否为首次运行或上次上传大小为0
200
+ if last_uploaded_size == -1:
201
+ print("首次运行,正在执行上传...")
202
+ update_last_uploaded_size(file_size) # 更新为当前文件大小
203
+
204
+ with open(metadata_file_path, 'w') as json_fid:
205
+ json.dump(kaggle_metadata, json_fid)
206
+
207
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
208
+ # kaggle datasets version -m 'new version message' -p /a
209
+ last_uploaded_size = file_size
210
+
211
+ elif file_size > last_uploaded_size:
212
+ print(f"新文件 {zip_file_path} 大于上次上传的大小,正在执行上传...")
213
+ update_last_uploaded_size(file_size) # 更新元数据中的最后一次上传大小
214
+
215
+ with open(metadata_file_path, 'w') as json_fid:
216
+ json.dump(kaggle_metadata, json_fid)
217
+
218
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
219
+ last_uploaded_size = file_size
220
+
221
+ else:
222
+ print(f"新文件 {zip_file_path} 不大于上次上传的大小,跳过")
223
+
224
+
225
+ def repeat_task():
226
+ print('------打包线程启动-------------')
227
+ while True:
228
+ print('等待打包')
229
+ time.sleep(600)
230
+ compress_folder()
231
+ print('------打包线程结束-------------')
232
+ # repeat_task()
233
+ # compress_folder()
234
+
235
+ import os
236
+ import subprocess
237
+ import pexpect
238
+
239
+ def generate_ssh_key():
240
+ # 生成 SSH 密钥对,并捕获输出和错误信息
241
+ os.system("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub")
242
+ keygen_command = "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''"
243
+ try:
244
+ result = subprocess.run(keygen_command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
245
+ print("SSH key pair generated.")
246
+ print(result.stdout.decode()) # 打印标准输出信息(如成功消息)
247
+ except subprocess.CalledProcessError as e:
248
+ print(f"Failed to generate SSH key: {e.stderr.decode() if e.stderr else e}")
249
+
250
+ def copy_public_key_to_remote(host, port, user, password):
251
+ # 使用 pexpect 自动输入密码来复制公钥
252
+ try:
253
+ command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}"
254
+ child = pexpect.spawn(command)
255
+
256
+ # 等待密码提示并发送密码
257
+ child.expect("password:", timeout=10) # 增加超时时间
258
+ child.sendline(password)
259
+
260
+ # 等待命令完成并输出结果
261
+ child.expect(pexpect.EOF)
262
+
263
+ print(child.before.decode()) # 打印输出结果
264
+
265
+ except Exception as e:
266
+ print(f"An error occurred: {e}")
267
+
268
+
269
+ # 生成 SSH 密钥对
270
+ generate_ssh_key()
271
+
272
+ # 复制公钥到远程服务器
273
+ copy_public_key_to_remote(frp_url, ssh_port, "root", "qilan")
274
+
275
+
276
+
277
+ def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
278
+ """创建一个带重试机制的请求会话"""
279
+ session = session or requests.Session()
280
+ retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
281
+ adapter = HTTPAdapter(max_retries=retry)
282
+ session.mount('http://', adapter)
283
+ session.mount('https://', adapter)
284
+ return session
285
+
286
+ def check_api1():
287
+ # 第一次检查 SillyTavern 是否启��
288
+ thread_started = False # 在函数内初始化标志变量
289
+ n=0
290
+ while True:
291
+ n = n + 1
292
+ if st_status == False and n > 50:
293
+ print("/sillytavern 文件不存在,结束检测")
294
+ break
295
+ try:
296
+ url = "http://127.0.0.1:8000/v1"
297
+ response = requests.get(url, timeout=30)
298
+
299
+ # 检查响应状态码
300
+ if response.status_code == 403:
301
+ print("SillyTavern已经启动")
302
+ break # 接口正常,退出循环
303
+
304
+ # 如果不是 403,打印其他信息
305
+ print("SillyTavern未启动,状态码:", response.status_code)
306
+
307
+ except requests.exceptions.RequestException as e:
308
+ print(f"SillyTavern未启动3: {e}") # 打印具体错误信息
309
+
310
+ time.sleep(5) # 等待5秒后重试
311
+
312
+ print('开始检测接口状态')
313
+ Service_status = False
314
+ # 第二次检查接口状态
315
+ n = 0
316
+ while True:
317
+ n = n + 1
318
+ if st_status == False and n > 50:
319
+ print("/sillytavern 文件不存在,结束检测")
320
+ break
321
+ if Service_status:
322
+ print("结束检测")
323
+ break
324
+ url = f"{st_url}/csrf-token" # 确保这个 URL 是正确的
325
+ try:
326
+ response = requests_retry_session().get(url, timeout=30)
327
+ response.raise_for_status() # 检查响应状态
328
+ # 尝试解析 JSON 响应
329
+ response_json = response.json() # 获取 JSON 内容
330
+ print(url,"接口返回信息:", response_json)
331
+ if "token" in response_json:
332
+ print("检测到 token")
333
+ try:
334
+ subprocess.run(f"rsync -avz -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{frp_url}:/sillytavern/ /sillytavern/", shell=True, check=True)
335
+ except subprocess.CalledProcessError as e:
336
+ print(f"Rsync failed with return code: {e.returncode}")
337
+ print(f"Command output: {e.output}")
338
+ # subprocess.run(f"rsync -avz -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{frp_url}:/sillytavern/ /sillytavern/", shell=True, check=True)
339
+ # break # 跳出循环
340
+ else:
341
+ print("接口返回信息:", response_json)
342
+
343
+ except requests.exceptions.ConnectionError as e:
344
+ print(f"接口异常1: {e}")
345
+ # threading.Thread(target=Frpc, daemon=True).start()
346
+ break
347
+
348
+ except requests.exceptions.Timeout as e:
349
+ print(f"接口异常2: {e}")
350
+ # threading.Thread(target=Frpc, daemon=True).start()
351
+ break
352
+
353
+ except requests.exceptions.RequestException as e:
354
+ print(f"接口异常3: {e}")
355
+ # threading.Thread(target=Frpc, daemon=True).start()
356
+ break
357
+
358
+ time.sleep(5) # 等待5秒后重试
359
+
360
+
361
+ def frp(config_data1,config_file_path,backstage):
362
+ print('-----------FRP开始-------------')
363
+ '''FRP配置'''
364
+ os.system("mkdir -p /content/frp")
365
+ os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
366
+ os.system("chmod +x /content/frp/frpc")
367
+ # config_file_path = '/content/frp/frpc.ini'
368
+ with open(config_file_path, 'w') as config_file:
369
+ config_file.write(config_data1)
370
+ # frpc 启动命令和参数
371
+ frpc_cmd = ['/content/frp/frpc', '-c', config_file_path]
372
+ if backstage:
373
+ subprocess.Popen(frpc_cmd)
374
+ else:
375
+ subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
376
+ print('-----------FPR结束-------------')
377
+ # /content/frp/frpc -c /content/frp/frpc.ini
378
+
379
+ import requests
380
+ import re
381
+
382
+ def get_current_ip():
383
+ """获取当前公共 IP 地址"""
384
+ response = requests.get("https://ipinfo.io/ip")
385
+ return response.text.strip()
386
+
387
+ def get_geo_info(ip_address):
388
+ """根据 IP 地址获取地理位置信息"""
389
+ url = f"https://api.qjqq.cn/api/Local"
390
+ headers = {
391
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
392
+ }
393
+
394
+ response = requests.get(url, headers=headers)
395
+
396
+ if response.status_code == 200:
397
+ geo_info = response.json() # 解析为 JSON 格式
398
+
399
+ if geo_info['code'] == 200:
400
+ data = geo_info['data']
401
+ return {
402
+ 'ip': data['ip'],
403
+ 'country': data['country'],
404
+ 'isp': data['isp']
405
+ }
406
+ else:
407
+ print("无法获取地理位置信息")
408
+ return None
409
+ else:
410
+ print(f"请求失败, 状态码: {response.status_code}")
411
+ return None
412
+
413
+ def replace_ip_and_country_in_file(file_path):
414
+ try:
415
+ # 获取当前 IP 地址
416
+ ip_address = get_current_ip()
417
+ print(f"获取到当前 IP: {ip_address}")
418
+
419
+ # 获取地理位置信息
420
+ geo_info = get_geo_info(ip_address)
421
+
422
+ if geo_info is not None:
423
+ print(f"获取到地理信息: {geo_info}")
424
+
425
+ # 读取文件内容
426
+ with open(file_path, 'r', encoding='utf-8') as file:
427
+ content = file.read()
428
+ # print(f"读取到的文件内容: {content}")
429
+
430
+ # 使用正则表达式匹配 "IP[xxx]国家[yyy]" 的格式
431
+ pattern = r'IP\[.*?\]国家\[.*?\]'
432
+ replacement = f'机子IP[{geo_info["ip"]}]国家[{geo_info["country"]}] ISP[{geo_info["isp"]}]'
433
+ new_content = re.sub(pattern, replacement, content)
434
+
435
+ # print(f"替换后的内容: {new_content}")
436
+
437
+ # 将修改后的内容写回文件
438
+ with open(file_path, 'w', encoding='utf-8') as file:
439
+ file.write(new_content)
440
+
441
+ print(f"成功更新为: IP[{geo_info['ip']}] 国家[{geo_info['country']}] ISP[{geo_info['isp']}]")
442
+
443
+ except FileNotFoundError:
444
+ print(f"错误: 文件 {file_path} 不存在。")
445
+ except IOError as e:
446
+ print(f"IO 错误: {e}")
447
+ except Exception as e:
448
+ print(f"发生其他错误: {e}")
449
+
450
+
451
+
452
+ def SillyTavern():
453
+ print('-----------SillyTavern开始-------------')
454
+ # 创建目录并写入 kaggle.json
455
+ os.system("mkdir -p ~/.kaggle")
456
+ file_path = '/root/.kaggle/kaggle.json'
457
+ with open(file_path, 'w') as json_file:
458
+ json.dump(ini_content, json_file, indent=4)
459
+ os.system("chmod 600 ~/.kaggle/kaggle.json")
460
+
461
+ clear_output()
462
+
463
+ os.system("rm -r /a /sillytavern /*.zi* /SillyTavern/")
464
+ os.system("mkdir -p /sillytavern")
465
+ os.chdir('/')
466
+ os.system("kaggle datasets download xovale7506/sillytavern2-data")
467
+ # 检查文件是否存在
468
+ if not os.path.exists('/sillytavern2-data.zip'):
469
+ print(f"文件 /sillytavern2-data.zip 不存在,程序将结束。")
470
+ st_status = False
471
+ # 如果文件存在,可以继续执行后续代码
472
+ print(f"文件 /sillytavern2-data.zip 存在,继续执行程序。")
473
+ # # 解压 sillytavern.zip
474
+ os.system("7z x /sillytavern2-data.zip -o/ -y")
475
+ os.system("mv /sillytavern.zip1 /sillytavern.zip")
476
+ os.system("7z x /sillytavern.zip -o/sillytavern -y")
477
+ os.system("rm *.zip")
478
+ clear_output()
479
+
480
+ # # 拉取最新版本
481
+ # !git clone https://github.com/SillyTavern/SillyTavern.git
482
+ # 强制替换掉备份
483
+ # !rsync -a --delete /SillyTavern/* /sillytavern/
484
+
485
+
486
+ threading.Thread(target=Oneapi, daemon=True).start()
487
+ os.chdir('/sillytavern')
488
+ replace_ip_and_country_in_file('/sillytavern/public/login.html')
489
+ os.system("ls")
490
+ os.system("nvm install node")
491
+ os.system("nvm use node")
492
+ os.system("npm install -y")
493
+ try:
494
+ subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
495
+ except subprocess.CalledProcessError as e:
496
+ print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
497
+ print("Output:", e.output)
498
+ os.chdir('/sillytavern')
499
+ subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
500
+ subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
501
+ subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
502
+ subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
503
+ print('-----------SillyTavern结束-------------')
504
+ # os.system("yes | sh start.sh -y")
505
+
506
+ # commands = [
507
+ # 'yes | sh start.sh -y'
508
+ # ]
509
+ # run_commands(commands)
510
+ threading.Thread(target=SillyTavern, daemon=True).start()
511
+ check_api1()
512
+ if not os.path.exists('/sillytavern2-data.zip'):
513
+ # threading.Thread(target=repeat_task, daemon=True).start() #压缩备份
514
+ # backup_thread = threading.Thread(target=repeat_task, daemon=True)
515
+ # backup_thread.start()
516
+ print("开始衔接")
517
+ Service_status = True
518
+ # frp(config_data2,'/content/frp/frpc2.ini',True)
519
+ # frp(config_data,'/content/frp/frpc.ini',False)
520
+ # 以线程的形式运行 frp 任务
521
+ frp_thread1 = threading.Thread(target=frp, args=(config_data2, '/content/frp/frpc2.ini', True))
522
+ frp_thread1.start()
523
+ frp_thread2 = threading.Thread(target=frp, args=(config_data, '/content/frp/frpc.ini', False))
524
+ frp_thread2.start()
525
+ while True:
526
+ if backup_thread.is_alive():
527
+ print("备份线程仍在运行...")
528
+ else:
529
+ print("备份线程已停止.")
530
+ # backup_thread = threading.Thread(target=repeat_task, daemon=True)
531
+ # backup_thread.start()
532
+ # break
533
+ try:
534
+ # 检查 /sillytavern/start.sh 是否在运行
535
+ subprocess.check_output(['pgrep', '-f', '/sillytavern/start.sh'])
536
+ # print("脚本正在运行。")
537
+ except subprocess.CalledProcessError:
538
+ print("脚本未运行。退出循环。")
539
+ compress_folder()
540
+ break
541
+ time.sleep(5)
542
+
543
+ else:
544
+ print("/sillytavern 文件不存在结束执行")