Qilan2 commited on
Commit
1ea8375
·
verified ·
1 Parent(s): 05749ae

Create server5.py

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