Qilan2 commited on
Commit
ff6b63d
·
verified ·
1 Parent(s): 380f0c3

Update server9-bf.py

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