Qilan2 commited on
Commit
4e11dfe
·
verified ·
1 Parent(s): 1479e04

Create server7.py

Browse files
Files changed (1) hide show
  1. server7.py +677 -0
server7.py ADDED
@@ -0,0 +1,677 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ini_content = {"username":"ighlnvd551","key":"14dee8c2e790b386ca7a61e974537d66"}
2
+ frp_url = '119.8.118.149'
3
+ ssh_port = '7080'
4
+ ssh_url = '43.129.165.236'
5
+ st_url = f'http://{frp_url}:7078'
6
+ huggingface_name = 'ighlnvd551'
7
+ huggingface_Data_name = 'qilan-st7'
8
+ configs = [
9
+ ("""
10
+ [common]
11
+ server_addr = 47.237.156.222
12
+ server_port = 7000
13
+
14
+ [safsa77]
15
+ type = tcp
16
+ local_ip = 127.0.0.1
17
+ local_port = 8000
18
+ remote_port = 7084
19
+
20
+ [sascb2f77]
21
+ type = tcp
22
+ local_ip = 127.0.0.1
23
+ local_port = 22
24
+ remote_port = 7085
25
+ """, '/content/frp/frpc.ini'),
26
+ (f"""
27
+ [common]
28
+ server_addr = {frp_url}
29
+ server_port = 7000
30
+ token = qilan
31
+ [kkjmk7]
32
+ type = tcp
33
+ local_ip = 127.0.0.1
34
+ local_port = 8000
35
+ remote_port = 7077
36
+ """, '/content/frp/frpc1.ini'),
37
+ ("""
38
+ [common]
39
+ server_addr = 124.156.207.7
40
+ server_port = 7000
41
+ [kjas7]
42
+ type = tcp
43
+ local_ip = 127.0.0.1
44
+ local_port = 8000
45
+ remote_port = 7077
46
+ """, '/content/frp/frpc2.ini'),
47
+ ("""
48
+ [common]
49
+ server_addr = 8.217.51.145
50
+ server_port = 7000
51
+ [kja1sh7]
52
+ type = tcp
53
+ local_ip = 127.0.0.1
54
+ local_port = 8000
55
+ remote_port = 7077
56
+ """, '/content/frp/frpc3.ini'),
57
+ ("""
58
+ [common]
59
+ server_addr = 8.210.221.90
60
+ server_port=7000
61
+ [kkji1mk7]
62
+ type=tcp
63
+ local_ip=127.0.0.1
64
+ local_port=8000
65
+ remote_port=7077
66
+ """, '/content/frp/frpc4.ini'),
67
+ (f"""
68
+ [common]
69
+ server_addr = {ssh_url}
70
+ server_port=7000
71
+ [kkji1mk7]
72
+ type=tcp
73
+ local_ip=127.0.0.1
74
+ local_port=22
75
+ remote_port={ssh_port}
76
+ """, '/content/frp/frpc5.ini')
77
+ ]
78
+ kaggle_metadata = {
79
+ "title": "Your Dataset Title",
80
+ "id": f"{huggingface_name}/{huggingface_Data_name}",
81
+ "licenses": [{"name": "CC0-1.0"}]
82
+ }
83
+ st_status = True
84
+ import subprocess
85
+ import os
86
+ import sys
87
+ import configparser
88
+ from IPython.display import clear_output
89
+ import urllib.request
90
+ from pathlib import Path
91
+ import requests
92
+ import json
93
+ import threading
94
+ import time
95
+ import pexpect
96
+ import socket
97
+ import time
98
+ import glob # 导入 glob 模块
99
+ from requests.adapters import HTTPAdapter
100
+ from requests.packages.urllib3.util.retry import Retry
101
+ os.system("rm -r /sync.sh")
102
+ os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
103
+ os.system("export LC_ALL=zh_CN.UTF-8")
104
+ # 创建 FRP 文件夹并下载 frpc 可执行文件。
105
+ os.system("mkdir -p /content/frp")
106
+ os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
107
+ os.system("chmod +x /content/frp/frpc")
108
+ # 更新软件包列表
109
+ def is_installed(package):
110
+ """Check if a package is installed."""
111
+ try:
112
+ # Check if the package is installed using dpkg (for apt packages)
113
+ subprocess.run(['dpkg', '-s', package], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
114
+ return True
115
+ except Exception as e:
116
+ return False
117
+
118
+ def install_package(package):
119
+ """Install a package using apt."""
120
+ print(f"Installing {package}...")
121
+ os.system(f"sudo apt install {package} -y")
122
+ def update():
123
+ print('-----------更新软件包列表开始-------------')
124
+ # os.system("sudo apt update")
125
+ # 安装 Node.js 和 npm
126
+ # os.system("sudo apt install nodejs npm -y")
127
+ # # 全局安装 forever
128
+ # os.system("sudo npm install -g forever")
129
+ if not is_installed('nodejs'):
130
+ install_package('nodejs')
131
+
132
+ if not is_installed('npm'):
133
+ install_package('npm')
134
+ # 安装 p7zip-full
135
+ os.system("sudo apt install p7zip-full -y")
136
+ os.system("pip install -U kaggle")
137
+ os.system("pip uninstall -y kaggle > /dev/null 2>&1")
138
+ os.system("pip install kaggle==1.5.6 > /dev/null 2>&1")
139
+ # os.system("apt-get install inotify-tools")
140
+ os.system("pip install ruamel.yaml") # install ruamel.yaml to solve the import issue
141
+ os.system("pip install pexpect")
142
+ os.system("pip install pytz")
143
+ os.system('apt-get install pigz')
144
+ os.system('apt-get install pv')
145
+ print('-----------更新软件包列表结束-------------')
146
+ update()
147
+
148
+
149
+ from ruamel.yaml import YAML
150
+ clear_output(wait=True) # 清除输出
151
+
152
+ def kill_frpc_processes():
153
+ try:
154
+ # 使用pkill命令结束所有frpc进程
155
+ subprocess.run(['pkill', '-f', 'frpc'], check=True)
156
+ print("所有frpc进程已被结束。")
157
+ except subprocess.CalledProcessError as e:
158
+ # 如果pkill命令失败,打印错误信息
159
+ print(f"结束frpc进程时出错: {e}")
160
+ kill_frpc_processes()
161
+
162
+
163
+ # SSH
164
+ def run_command(command):
165
+ try:
166
+ subprocess.run(command, check=True, shell=True)
167
+ except subprocess.CalledProcessError as e:
168
+ print(f"An error occurred: {e}")
169
+ def ssh():
170
+ print('-----------SSH开始-------------')
171
+ subprocess.run("apt update", check=True, shell=True)
172
+ subprocess.run("apt install openssh-server -y", check=True, shell=True)
173
+ subprocess.run("apt-get install vim -y", check=True, shell=True)
174
+
175
+ config_client_cmd = "sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config"
176
+ subprocess.run(config_client_cmd, check=True, shell=True)
177
+ config_server_cmd = "sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config"
178
+ subprocess.run(config_server_cmd, check=True, shell=True)
179
+ run_command("systemctl restart ssh")
180
+
181
+ os.system("/etc/init.d/ssh restart")
182
+ os.system("echo 'root:qilan' | sudo chpasswd")
183
+ os.system("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
184
+ os.system("service ssh restart ")
185
+ os.system("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
186
+ print('-----------SSH结束-------------')
187
+ ssh()
188
+ clear_output()
189
+
190
+
191
+
192
+ # 创建一个锁
193
+ lock = threading.Lock()
194
+ data_folder = '/root/SillyTavern' # 要压缩的目录
195
+ zip_file_path = '/a/sillytavern.tar.gz' # 输出的 tar.gz 文件路径
196
+ metadata_file_path = '/a/dataset-metadata.json'
197
+ last_uploaded_size = -1
198
+
199
+
200
+ def update_last_uploaded_size(size):
201
+ global last_uploaded_size
202
+ last_uploaded_size = size
203
+
204
+ def get_folder_size(folder):
205
+ """使用 du 命令获取文件夹的总大小(字节数)"""
206
+ result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
207
+ if result.returncode == 0:
208
+ size = result.stdout.split()[0] # 获取大小
209
+ return int(size)
210
+ else:
211
+ print(f"Error calculating size: {result.stderr.decode()}")
212
+ return 0
213
+
214
+ def compress_folder():
215
+ global last_uploaded_size # 声明使用全局变量
216
+ # 清理并创建目录 /a
217
+ if os.path.exists('/a'):
218
+ subprocess.run(['rm', '-r', '/a/'])
219
+ os.makedirs('/a', exist_ok=True)
220
+ with lock: # 使用锁
221
+ # 获取当前文件夹的大小
222
+ current_folder_size = get_folder_size(data_folder)
223
+ print(f"当前文件夹大小: {current_folder_size} 字节")
224
+
225
+ # 判断文件夹大小是否大于 800MB (800MB = 800 * 1024 * 1024 字节)
226
+ if current_folder_size < (800 * 1024 ** 2):
227
+ print("文件夹小于800MB,不进行上传和压缩。")
228
+ return
229
+
230
+ # 如果是首次运行或者文件夹大小不同于上次上传,进行压缩
231
+ if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
232
+ print('开始压缩数据')
233
+ try:
234
+ # 执行压缩
235
+ result = subprocess.run(
236
+ f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
237
+ shell=True,
238
+ check=True,
239
+ stdout=subprocess.DEVNULL, # 将标准输出重定向到 /dev/null
240
+ stderr=subprocess.DEVNULL # 将标准错误也重定向到 /dev/null
241
+ )
242
+ except subprocess.CalledProcessError as e:
243
+ print(f"命令失败,返回代码: {e.returncode}")
244
+ return
245
+
246
+ print('压缩完成')
247
+ file_path = "/a/sillytavern.ctk"
248
+ subprocess.run(['mv', zip_file_path, file_path])
249
+ print(f"数据压缩为 {file_path}")
250
+
251
+ file_size = os.path.getsize(file_path) # 获取压缩包的大小
252
+ print('文件大小:', file_size)
253
+
254
+ if file_size < (800 * 1024 ** 2): # 判断压缩后的大小是否小于 800MB
255
+ print("压缩文件小于800MB,不进行上传。")
256
+ return
257
+
258
+ # 执行上传
259
+ if last_uploaded_size == -1:
260
+ print("首次运行,正在执行上传...")
261
+ update_last_uploaded_size(file_size)
262
+
263
+ with open(metadata_file_path, 'w') as json_fid:
264
+ json.dump(kaggle_metadata, json_fid)
265
+
266
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
267
+ last_uploaded_size = file_size
268
+ else:
269
+ print(f"新文件大小 {file_size} 大于上次上传的大小,正在执行上传...")
270
+ update_last_uploaded_size(file_size)
271
+
272
+ with open(metadata_file_path, 'w') as json_fid:
273
+ json.dump(kaggle_metadata, json_fid)
274
+
275
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
276
+ last_uploaded_size = file_size
277
+
278
+ else:
279
+ print(f"新文件夹大小 {current_folder_size} 不大于上次上传的大小,跳过")
280
+
281
+ def repeat_task():
282
+ print('------打包线程启动-------------')
283
+ while True:
284
+ print('等待打包')
285
+ time.sleep(18000)
286
+ compress_folder()
287
+ print('------打包线程结束-------------')
288
+ # repeat_task()
289
+ # compress_folder()
290
+
291
+
292
+
293
+ def generate_ssh_key():
294
+ # 生成 SSH 密钥对,并捕获输出和错误信息
295
+ os.system("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub")
296
+ keygen_command = "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''"
297
+ try:
298
+ result = subprocess.run(keygen_command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
299
+ print("SSH key pair generated.")
300
+ print(result.stdout.decode()) # 打印标准输出信息(如成功消息)
301
+ except subprocess.CalledProcessError as e:
302
+ print(f"Failed to generate SSH key: {e.stderr.decode() if e.stderr else e}")
303
+
304
+ def copy_public_key_to_remote(host, port, user, password):
305
+ # 使用 pexpect 自动输入密码来复制公钥
306
+ try:
307
+ command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}"
308
+ child = pexpect.spawn(command)
309
+
310
+ # 等待密码提示并发送密码
311
+ child.expect("password:", timeout=10) # 增加超时时间
312
+ child.sendline(password)
313
+
314
+ # 等待命令完成并输出结果
315
+ child.expect(pexpect.EOF)
316
+
317
+ print(child.before.decode()) # 打印输出结果
318
+
319
+ except Exception as e:
320
+ print(f"An error occurred: {e}")
321
+
322
+
323
+ # 生成 SSH 密钥对
324
+ generate_ssh_key()
325
+ os.system('chmod 600 ~/.ssh/id_rsa')
326
+ # 复制公钥到远程服务器
327
+ copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
328
+
329
+
330
+
331
+ def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
332
+ """创建一个带重试机制的请求会话"""
333
+ session = session or requests.Session()
334
+ retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
335
+ adapter = HTTPAdapter(max_retries=retry)
336
+ session.mount('http://', adapter)
337
+ session.mount('https://', adapter)
338
+ return session
339
+
340
+ def write_rsyncd_conf(path, port=7075):
341
+ rsyncd_conf_content = f"""
342
+ port = {port}
343
+
344
+ [qilan]
345
+ path = {path}
346
+ comment = My rsync module
347
+ read only = no
348
+ list = yes
349
+ """
350
+ with open('/etc/rsyncd.conf', 'w') as f:
351
+ f.write(rsyncd_conf_content.strip())
352
+ print(f"Successfully wrote to /etc/rsyncd.conf for module .")
353
+ os.system("sudo rsync --daemon")
354
+ os.system("sudo rsync --daemon")
355
+ os.system("sudo rsync --daemon")
356
+ os.system("sudo rsync --daemon")
357
+
358
+ # write_rsyncd_conf(data_folder)
359
+ # os.system("ps aux | grep rsync")
360
+ import os
361
+ import time
362
+ import requests
363
+ import subprocess
364
+ import logging
365
+
366
+ # 配置日志
367
+ logging.basicConfig(level=logging.INFO)
368
+
369
+ def check_api1():
370
+ # 第一次检查 SillyTavern 是否启动
371
+ thread_started = False
372
+ n = 0
373
+ while True:
374
+ n += 1
375
+ if not os.path.exists(data_folder):
376
+ logging.error(f"/sillytavern/ 文件不存在,结束检测")
377
+ break
378
+ try:
379
+ url = "http://127.0.0.1:8000/v1"
380
+ response = requests.get(url, timeout=30)
381
+
382
+ if response.status_code == 403:
383
+ print("SillyTavern已经启动")
384
+ break
385
+
386
+ print("SillyTavern未启动,状态码:", response.status_code, n)
387
+
388
+ except requests.exceptions.RequestException as e:
389
+ print(f"SillyTavern未启动3: {e}, 尝试次数: {n}")
390
+
391
+ time.sleep(5)
392
+
393
+ print('ST本地已经运行,开始检测接口状态')
394
+ Service_status = False
395
+ n = 0
396
+ nn = 0
397
+ while True:
398
+ n += 1
399
+ if not os.path.exists(data_folder):
400
+ print(f"/sillytavern/ 文件不存在,结束检测")
401
+ break
402
+ if Service_status:
403
+ print("结束检测")
404
+ break
405
+ if nn > 2:
406
+ break
407
+ url = f"{st_url}/csrf-token"
408
+ try:
409
+ response = requests_retry_session().get(url, timeout=30)
410
+ response.raise_for_status()
411
+ response_json = response.json()
412
+ print("%s 接口返回信息: %s", url, response_json) # 修正日志记录
413
+ if "token" in response_json:
414
+ print("检测到 token")
415
+ try:
416
+ subprocess.run(f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",shell=True, check=True)
417
+ # break # 如果成功,跳出重试循环
418
+ except subprocess.CalledProcessError as e:
419
+ nn += 1
420
+ print(f"Rsync 失败,返回码: {e.returncode}, 尝试次数: {nn}")
421
+ generate_ssh_key() # 处理 SSH 密钥生成
422
+ else:
423
+ print("%s 接口返回信息: %s", url, response_json) # 修正日志记录
424
+ except requests.exceptions.ConnectionError as e:
425
+ print(f"接口异常1: {e}, 尝试次数: {n}, nn: {nn}")
426
+ # time.sleep(3)
427
+ nn += 1
428
+ if nn > 5:
429
+ break
430
+ except requests.exceptions.Timeout as e:
431
+ print(f"接口异常2: {e}, 尝试次数: {n}")
432
+ break
433
+ except requests.exceptions.RequestException as e:
434
+ print(f"接口异常3: {e}, 尝试次数: {n}")
435
+ break
436
+
437
+ time.sleep(5)
438
+
439
+
440
+
441
+
442
+ def frp(configs, backstage):
443
+ print('-----------FRP开始-------------')
444
+ # 遍历所有配置并启动 FRP。
445
+ for config_data, config_file_path in configs:
446
+ with open(config_file_path, 'w') as config_file:
447
+ config_file.write(config_data)
448
+ # 启动 frpc 命令和参数。
449
+ frpc_cmd=['/content/frp/frpc', '-c', config_file_path]
450
+
451
+ if backstage:
452
+ subprocess.Popen(frpc_cmd)
453
+ else:
454
+ subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
455
+ print('-----------FRP结束-------------')
456
+
457
+ import requests
458
+ import re
459
+ from datetime import datetime, timedelta
460
+ import psutil # 用于获取系统启动时间
461
+ import pytz # 用于处理时区
462
+
463
+ def get_current_ip():
464
+ """获取当前公共 IP 地址"""
465
+ response = requests.get("https://ipinfo.io/ip")
466
+ return response.text.strip()
467
+
468
+ def get_geo_info(ip_address):
469
+ """根据 IP 地址获取地理位置信息"""
470
+ url = f"https://api.qjqq.cn/api/Local"
471
+ headers = {
472
+ "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"
473
+ }
474
+
475
+ response = requests.get(url, headers=headers)
476
+
477
+ if response.status_code == 200:
478
+ geo_info = response.json()
479
+
480
+ if geo_info['code'] == 200:
481
+ data = geo_info['data']
482
+ return {
483
+ 'ip': data['ip'],
484
+ 'country': data['country'],
485
+ 'isp': data['isp']
486
+ }
487
+ return None
488
+
489
+ def get_next_relay_time():
490
+ """获取下一次接力时间(系统启动时间+12小时,转换为中国时区)"""
491
+ # 获取系统启动时间
492
+ boot_time = datetime.fromtimestamp(psutil.boot_time())
493
+ # 设置为UTC时区
494
+ utc = pytz.UTC
495
+ boot_time = utc.localize(boot_time)
496
+ # 转换为中国时区
497
+ china_tz = pytz.timezone('Asia/Shanghai')
498
+ boot_time_china = boot_time.astimezone(china_tz)
499
+ # 加上12小时
500
+ next_time = boot_time_china + timedelta(hours=12)
501
+ return next_time.strftime("%Y-%m-%d %H:%M:%S")
502
+
503
+ def replace_info_in_file(file_path):
504
+ try:
505
+ # 获取当前 IP 地址和地理信息
506
+ ip_address = get_current_ip()
507
+ geo_info = get_geo_info(ip_address)
508
+ next_relay_time = get_next_relay_time()
509
+
510
+ if geo_info is not None:
511
+ # 读取文件内容
512
+ with open(file_path, 'r', encoding='utf-8') as file:
513
+ content = file.read()
514
+
515
+ # 替换接力时间
516
+ time_pattern = r'接力时间\[.*?\]'
517
+ time_replacement = f'接力时间[{next_relay_time}]'
518
+ content = re.sub(time_pattern, time_replacement, content)
519
+
520
+ # 替换 IP 信息
521
+ ip_pattern = r'IP\[.*?\]\s*国家\s*\[.*?\]\s*IPS\[.*?\]'
522
+ ip_replacement = f'IP[{ip_address}] 国家 [{geo_info["country"]}] IPS[{geo_info["isp"]}]'
523
+ content = re.sub(ip_pattern, ip_replacement, content)
524
+
525
+ # 写回文件
526
+ with open(file_path, 'w', encoding='utf-8') as file:
527
+ file.write(content)
528
+
529
+ print(f"成功更新信息:")
530
+ print(f"接力时间: {next_relay_time}")
531
+ print(f"IP信息: IP[{ip_address}] 国家 [{geo_info['country']}] IPS[{geo_info['isp']}]")
532
+
533
+ except Exception as e:
534
+ print(f"发生错误: {e}")
535
+
536
+
537
+ def monitor_port():
538
+ while True:
539
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
540
+ result = sock.connect_ex(('localhost', 8000))
541
+ if result == 0:
542
+ print(f"端口 8000 正在使用中")
543
+ else:
544
+ print(f"端口 8000 未被使用")
545
+ # 读取 config.ini 中的 monitor_port_enabled 配置项
546
+ config = configparser.ConfigParser()
547
+ config.read('/config.ini')
548
+ monitor_port_enabled = config.getboolean('general', 'monitor_port_enabled', fallback=False)
549
+ if monitor_port_enabled:
550
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
551
+ backup_thread.start()
552
+ else:
553
+ print(f"monitor_port_enabled 为False跳过")
554
+
555
+ time.sleep(5) # 每5秒检查一次
556
+ def Run_SillyTavern():
557
+ os.chdir(data_folder)
558
+ try:
559
+ # 启动 Node.js 服务器,并将输出重定向到 /dev/null
560
+ subprocess.run(f'nohup sh -c "echo yes | sh {data_folder}/start.sh" > /server.log 2>&1 &', shell=True)
561
+ subprocess.run(f'nohup sh -c "echo yes | sh {data_folder}/start.sh" > /server.log 2>&1 &', shell=True)
562
+ subprocess.run(f'nohup sh -c "echo yes | sh {data_folder}/start.sh" > /server.log 2>&1 &', shell=True)
563
+ subprocess.run(f'nohup sh -c "echo yes | sh {data_folder}/start.sh" > /server.log 2>&1 &', shell=True)
564
+ subprocess.run(f'nohup sh -c "echo yes | sh {data_folder}/start.sh" > /server.log 2>&1 &', shell=True)
565
+ print("已尝试启动 server.js")
566
+ except subprocess.CalledProcessError as e:
567
+ print(f"命令失败,返回码: {e.returncode}")
568
+ except Exception as e: # 捕获所有其他异常
569
+ print(f"发生异常: {e}")
570
+
571
+ def SillyTavern():
572
+ print('-----------SillyTavern开始-------------')
573
+ # 创建目录并写入 kaggle.json
574
+ os.system("mkdir -p ~/.kaggle")
575
+ file_path = '/root/.kaggle/kaggle.json'
576
+ with open(file_path, 'w') as json_file:
577
+ json.dump(ini_content, json_file, indent=4)
578
+ os.system("chmod 600 ~/.kaggle/kaggle.json")
579
+
580
+ clear_output()
581
+
582
+ os.system(f"rm -r /a /sillytavern /*.zi* {data_folder}")
583
+ os.system(f"mkdir -p {data_folder}")
584
+ os.chdir('/')
585
+ print(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
586
+ # os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
587
+ download_n = 0
588
+ while True:
589
+ # 执行下载命令
590
+ if download_n > 6:
591
+ break
592
+ os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
593
+ # 检查文件是否存在
594
+ if os.path.exists(f'/{huggingface_Data_name}.zip'):
595
+ print(f"{huggingface_Data_name}.zip 下载成功!")
596
+ break # 跳出循环
597
+ print(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
598
+ download_n += 1
599
+ time.sleep(300) # 等待一段时间再重试(例如5秒
600
+ # os.system('kaggle datasets download xovale7506/sillytavern-data2')
601
+ # 检查文件是否存在
602
+ if not os.path.exists(f'/{huggingface_Data_name}.zip'):
603
+ print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。")
604
+ generate_ssh_key()
605
+ copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
606
+ subprocess.run(f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",shell=True, check=True)
607
+ else:
608
+
609
+ # 如果文件存在,可以继续执行后续代码
610
+ print(f"文件 /{huggingface_Data_name}.zip 存在,继续执行程序。")
611
+ # # 解压 sillytavern.zip
612
+ # os.system("rm *.zip")
613
+
614
+ os.system(f"7z x /{huggingface_Data_name}.zip -o/ -y")
615
+ # os.system("mv /sillytavern.zip1 /sillytavern.zip")
616
+ # os.system("7z x /sillytavern.zip -o/sillytavern -y")
617
+ os.system("mv /sillytavern.tck sillytavern.tar.gz")
618
+ os.system("mv /sillytavern.ctk sillytavern.tar.gz")
619
+ os.system("ls /")
620
+ # os.system("tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz")
621
+ os.system(f"tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz > /dev/null")
622
+ # os.system("pv /sillytavern.tar.gz | tar -xvpf - -C / --use-compress-program=pigz")
623
+
624
+ print('更新文件')
625
+ # os.system('git pull --rebase --autostash')
626
+
627
+ os.chdir(data_folder)
628
+ os.system(f"ls {data_folder}")
629
+ os.system("nvm install node")
630
+ os.system("nvm use node")
631
+ os.system("npm install -y")
632
+ try:
633
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
634
+ except subprocess.CalledProcessError as e:
635
+ print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
636
+ print("Output:", e.output)
637
+ os.system(f"ls {data_folder}")
638
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
639
+ backup_thread.start()
640
+ os.system("rm -r /qilan-st2.zip /sillytavern.tar.gz")
641
+ print('-----------SillyTavern结束-------------')
642
+ threading.Thread(target=SillyTavern, daemon=True).start()
643
+ time.sleep(60)
644
+ check_api1()
645
+
646
+
647
+ # 创建 ConfigParser 对象
648
+ config = configparser.ConfigParser()
649
+ # 添加一个 'general' 部分
650
+ config.add_section('general')
651
+ # 设置 'monitor_port_enabled' 选项的值为 True
652
+ config.set('general', 'monitor_port_enabled', 'True')
653
+ # 将配置写入到 'config.ini' 文件中
654
+ with open('/config.ini', 'w') as configfile:
655
+ config.write(configfile)
656
+
657
+ if os.path.exists(f'{data_folder}/start.sh'):
658
+ replace_info_in_file(f'{data_folder}/public/login.html')
659
+ backup_thread = threading.Thread(target=repeat_task, daemon=True)#压缩备份
660
+ backup_thread.start()
661
+ print("开始衔接")
662
+ Service_status = True
663
+ frp(configs, True)
664
+ threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
665
+ while True:
666
+ if backup_thread.is_alive():
667
+ print("备份线程仍在运行...")
668
+ else:
669
+ print("备份线程已停止.")
670
+ backup_thread = threading.Thread(target=repeat_task, daemon=True)
671
+ backup_thread.start()
672
+ # break
673
+ time.sleep(5)
674
+
675
+ else:
676
+ print("/sillytavern 文件不存在结束执行")
677
+ compress_folder()