Qilan2 commited on
Commit
a42660c
·
verified ·
1 Parent(s): f947a79

Create server4.py

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