Qilan2 commited on
Commit
bcd69f7
·
verified ·
1 Parent(s): 0c49720

Update server6.py

Browse files
Files changed (1) hide show
  1. server6.py +486 -697
server6.py CHANGED
@@ -1,8 +1,8 @@
1
  ini_content = {"username":"hdsg142saa","key":"2da57ac0c245c1ebba26017f161d5558"}
2
  frp_url = '119.8.118.149'
3
- ssh_port = '7078'
4
  ssh_url = '43.135.135.22'
5
- st_url = f'http://{frp_url}:7076'
6
  huggingface_name = 'hdsg142saa'
7
  huggingface_Data_name = 'qilan-st5'
8
  configs = [
@@ -11,64 +11,64 @@ configs = [
11
  server_addr = 47.237.156.222
12
  server_port = 7000
13
 
14
- [safsa55]
15
  type = tcp
16
  local_ip = 127.0.0.1
17
  local_port = 8000
18
- remote_port = 7080
19
 
20
- [sascb2f55]
21
  type = tcp
22
  local_ip = 127.0.0.1
23
  local_port = 22
24
- remote_port = 7081
25
  """, '/content/frp/frpc.ini'),
26
  (f"""
27
  [common]
28
  server_addr = {frp_url}
29
  server_port = 7000
30
  token = qilan
31
- [kkjmk5]
32
  type = tcp
33
  local_ip = 127.0.0.1
34
  local_port = 8000
35
  remote_port = 7076
36
  """, '/content/frp/frpc1.ini'),
37
- ("""
38
- [common]
39
- server_addr = 47.237.78.158
40
- server_port = 7000
41
- [kjas2]
42
- type = tcp
43
- local_ip = 127.0.0.1
44
- local_port = 8000
45
- remote_port = 7075
46
- """, '/content/frp/frpc2.ini'),
47
- ("""
48
- [common]
49
- server_addr = 45.94.69.159
50
- server_port = 7000
51
- [kja1sh5]
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 = 43.128.135.88
60
- server_port=7000
61
- [kkji1mk5]
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
- [kkji1mk5]
72
  type=tcp
73
  local_ip=127.0.0.1
74
  local_port=22
@@ -81,13 +81,9 @@ kaggle_metadata = {
81
  "licenses": [{"name": "CC0-1.0"}]
82
  }
83
  st_status = True
84
- import os
85
- os.system("pip install paramiko")
86
- # 导入必要的模块
87
  import subprocess
88
-
89
  import sys
90
- import logging
91
  from IPython.display import clear_output
92
  import urllib.request
93
  from pathlib import Path
@@ -96,123 +92,71 @@ import json
96
  import threading
97
  import time
98
  import pexpect
99
- import glob
100
- import socket
101
- import re
102
- from datetime import datetime, timedelta
103
- import psutil
104
- import pytz
105
- import paramiko
106
  from requests.adapters import HTTPAdapter
107
  from requests.packages.urllib3.util.retry import Retry
108
- from ruamel.yaml import YAML
109
-
110
- # 配置日志
111
- logging.basicConfig(
112
- level=logging.INFO,
113
- format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
114
- )
115
- logger = logging.getLogger(__name__)
116
-
117
- # 文件和目录设置
118
- data_folder = '/root/SillyTavern' # 要压缩的目录
119
- zip_file_path = '/a/sillytavern.tar.gz' # 输出的 tar.gz 文件路径
120
- metadata_file_path = '/a/dataset-metadata.json'
121
-
122
- # 创建锁和共享变量
123
- lock = threading.Lock()
124
- last_uploaded_size = -1
125
- service_status = False
126
-
127
- # 初始设置
128
  os.system("rm -r /sync.sh")
129
  os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
130
  os.system("export LC_ALL=zh_CN.UTF-8")
131
  os.system("mkdir -p /content/frp")
132
- os.system("wget https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
133
  os.system("chmod +x /content/frp/frpc")
134
 
135
  # 更新软件包列表
136
  def is_installed(package):
137
- """检查软件包是否已安装"""
138
  try:
139
- subprocess.run(['dpkg', '-s', package],
140
- stdout=subprocess.PIPE,
141
- stderr=subprocess.PIPE,
142
- check=True)
143
  return True
144
- except subprocess.CalledProcessError:
145
  return False
146
 
147
  def install_package(package):
148
- """使用apt安装软件包"""
149
- logger.info(f"正在安装 {package}...")
150
- subprocess.run(
151
- f"sudo apt install {package} -y > /dev/null 2>&1",
152
- shell=True,
153
- check=False
154
- )
155
-
156
- def update_packages():
157
- """更新和安装所需软件包"""
158
- logger.info('��始更新软件包列表')
159
-
160
- # 安装必要的系统依赖
161
- packages = {
162
- 'system': ['nodejs', 'npm', 'pigz', 'pv', 'p7zip-full', 'openssh-server', 'vim'],
163
- 'python': ['kaggle==1.5.6', 'ruamel.yaml', 'pexpect', 'pytz', 'paramiko']
164
- }
165
-
166
- # 安装系统包
167
- for pkg in packages['system']:
168
- if not is_installed(pkg):
169
- install_package(pkg)
170
-
171
- # 安装Python包
172
- for pkg in packages['python']:
173
- if '==' in pkg:
174
- pkg_name = pkg.split('==')[0]
175
- pkg_version = pkg.split('==')[1]
176
- os.system(f"pip uninstall -y {pkg_name} > /dev/null 2>&1")
177
- os.system(f"pip install {pkg} > /dev/null 2>&1")
178
- else:
179
- os.system(f"pip install {pkg} > /dev/null 2>&1")
180
-
181
- logger.info('软件包列表更新完成')
182
 
183
  def kill_frpc_processes():
184
- """结束所有frpc进程"""
185
  try:
 
186
  subprocess.run(['pkill', '-f', 'frpc'], check=True)
187
- logger.info("所有frpc进程已被结束")
188
  except subprocess.CalledProcessError as e:
189
- logger.error(f"结束frpc进程时出错: {e}")
190
-
191
- # 运行系统更新
192
- update_packages()
193
- clear_output(wait=True) # 清除输出
194
-
195
- # 关闭可能运行的frpc进程
196
  kill_frpc_processes()
197
 
198
- def run_command(cmd, check=True, shell=True, silent=False):
199
- """运行系统命令的通用函数"""
200
- try:
201
- kwargs = {
202
- 'shell': shell,
203
- 'check': check
204
- }
205
-
206
- if silent:
207
- kwargs.update({
208
- 'stdout': subprocess.DEVNULL,
209
- 'stderr': subprocess.DEVNULL
210
- })
211
-
212
- return subprocess.run(cmd, **kwargs)
213
- except subprocess.CalledProcessError as e:
214
- logger.error(f"命令执行失败: {e}")
215
- return None
216
 
217
  # Oneapi中转
218
  def Oneapi():
@@ -242,88 +186,177 @@ def Oneapi():
242
  print('-----------Oneapi中转结束-------------')
243
  # Oneapi()
244
 
245
- # SSH相关功能
 
 
 
 
 
246
  def ssh():
247
- """安装和配置SSH服务器"""
248
- logger.info('开始配置SSH服务')
249
-
250
- # 安装SSH服务器
251
- run_command("apt update", silent=True)
252
- run_command("apt install openssh-server -y", silent=True)
253
- run_command("apt-get install vim -y", silent=True)
254
-
255
- # 配置SSH
256
- run_command("sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config")
257
- run_command("sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config")
258
  run_command("systemctl restart ssh")
259
- run_command("/etc/init.d/ssh restart")
260
- run_command("echo 'root:qilan' | sudo chpasswd")
261
- run_command("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
262
- run_command("service ssh restart")
263
- run_command("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
264
-
265
- logger.info('SSH服务配置完成')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
 
267
  def generate_ssh_key():
268
- """生成SSH密钥对"""
269
- logger.info("生成SSH密钥对")
270
- # 删除已有的SSH密钥
271
  os.system("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub")
272
-
273
- # 生成���的SSH密钥
274
  keygen_command = "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''"
275
  try:
276
- result = subprocess.run(
277
- keygen_command,
278
- shell=True,
279
- check=True,
280
- stdout=subprocess.PIPE,
281
- stderr=subprocess.PIPE
282
- )
283
- logger.info("SSH密钥对已生成")
284
-
285
- # 设置权限
286
- os.system('chmod 600 ~/.ssh/id_rsa')
287
- return True
288
  except subprocess.CalledProcessError as e:
289
- error_msg = e.stderr.decode() if e.stderr else str(e)
290
- logger.error(f"SSH密钥生成失败: {error_msg}")
291
- return False
292
 
293
  def copy_public_key_to_remote(host, port, user, password):
294
- """将公钥复制到远程服务器"""
295
- logger.info(f"正在将公钥复制到 {user}@{host}:{port}")
296
  try:
297
  command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}"
298
  child = pexpect.spawn(command)
299
 
300
  # 等待密码提示并发送密码
301
- child.expect("password:", timeout=15)
302
  child.sendline(password)
303
 
304
- # 等待命令完成
305
  child.expect(pexpect.EOF)
306
- logger.info("公钥已成功复制到远程服务器")
307
- return True
 
308
  except Exception as e:
309
- logger.error(f"复制公钥失败: {e}")
310
- return False
311
 
312
- def check_ssh_connection(host, port, username, password):
313
- """检查SSH连接是否可用"""
314
- try:
315
- client = paramiko.SSHClient()
316
- client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
317
- client.connect(hostname=host, port=int(port), username=username, password=password, timeout=10)
318
- client.close()
319
- logger.info(f"SSH连接到 {username}@{host}:{port} 成功")
320
- return True
321
- except Exception as e:
322
- logger.error(f"SSH连接失败: {e}")
323
- return False
324
 
 
 
 
 
 
 
325
  def write_rsyncd_conf(path, port=7071):
326
- """配置rsync守护进程"""
327
  rsyncd_conf_content = f"""
328
  port = {port}
329
  [qilan]
@@ -334,22 +367,16 @@ port = {port}
334
  """
335
  with open('/etc/rsyncd.conf', 'w') as f:
336
  f.write(rsyncd_conf_content.strip())
337
- logger.info(f"已配置rsync守护进程,端口为 {port}")
338
 
339
- # 启动rsync守护进程
340
- run_command("sudo rsync --daemon")
341
- run_command("ps aux | grep rsync", silent=True)
342
 
343
  def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
344
  """创建一个带重试机制的请求会话"""
345
  session = session or requests.Session()
346
- retry = Retry(
347
- total=retries,
348
- read=retries,
349
- connect=retries,
350
- backoff_factor=backoff_factor,
351
- status_forcelist=status_forcelist,
352
- )
353
  adapter = HTTPAdapter(max_retries=retry)
354
  session.mount('http://', adapter)
355
  session.mount('https://', adapter)
@@ -363,562 +390,324 @@ import logging
363
 
364
  import paramiko
365
 
366
- def monitor_port(port=8000, check_interval=5):
367
- """监控指定端口,如果未使用则重新启动SillyTavern"""
368
- logger.info(f"开始监控端口 {port}")
369
- while True:
370
- try:
371
- with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
372
- result = sock.connect_ex(('localhost', port))
373
- if result == 0:
374
- logger.info(f"端口 {port} 正在使用中")
375
- else:
376
- logger.warning(f"端口 {port} 未被使用,尝试重新启动SillyTavern")
377
- threading.Thread(target=Run_SillyTavern, daemon=True).start()
378
- except Exception as e:
379
- logger.error(f"端口监控异常: {e}")
380
-
381
- time.sleep(check_interval)
382
-
383
- def Run_SillyTavern():
384
- """运行SillyTavern服务器"""
385
- logger.info("尝试启动SillyTavern")
386
  try:
387
- # 确保在正确的目录中
388
- os.chdir(data_folder)
389
-
390
- # 多次尝试启动,提高成功率
391
- for i in range(5):
392
- logger.info(f"第{i+1}次尝试启动SillyTavern")
393
- result = run_command(f'yes | sh {data_folder}/start.sh', silent=True)
394
- if result and result.returncode == 0:
395
- logger.info("SillyTavern已成功启动")
396
- break
397
- time.sleep(2)
398
-
399
- logger.info("SillyTavern启动过程完成")
400
  except Exception as e:
401
- logger.error(f"启动SillyTavern时发生异常: {e}")
 
402
 
403
- def check_api_status():
404
- """检查SillyTavern API是否正常运行"""
405
- # 检查本地服务是否启动
406
- max_retries = 30
407
- retry_count = 0
408
-
409
- # 第一步:检查本地API是否启动
410
- logger.info("检查SillyTavern本地API是否启动")
411
- while retry_count < max_retries:
412
- retry_count += 1
413
-
 
414
  if not os.path.exists(data_folder):
415
- logger.error(f"数据目录 {data_folder} 不存在,终止检测")
416
- return False
417
-
418
  try:
419
  url = "http://127.0.0.1:8000/v1"
420
- response = requests.get(url, timeout=5)
421
-
422
  if response.status_code == 403:
423
- logger.info("SillyTavern本地API已启动")
424
  break
425
 
426
- logger.warning(f"SillyTavern未启动,状态码: {response.status_code},重试次数: {retry_count}")
 
427
  except requests.exceptions.RequestException as e:
428
- logger.warning(f"SillyTavern未启动: {e},重试次数: {retry_count}")
429
 
430
- if retry_count >= max_retries:
431
- logger.error("SillyTavern本地API启动检测超时")
432
- return False
433
-
434
  time.sleep(5)
435
 
436
- # 第二步:检查远程API是否可访问
437
- logger.info("本地API已启动,开始检测远程API状态")
438
- retry_count = 0
439
- retry_limit = 10
440
- sync_attempts = 0
441
-
442
- while retry_count < retry_limit:
443
- retry_count += 1
444
-
445
- if sync_attempts >= 3:
446
- logger.error("同步尝试次数过多,终止检测")
 
 
447
  break
448
-
449
  url = f"{st_url}/csrf-token"
450
  try:
451
- response = requests_retry_session().get(url, timeout=10)
452
  response.raise_for_status()
453
  response_json = response.json()
454
-
455
- logger.info(f"远程API返回信息: {response_json}")
456
-
457
  if "token" in response_json:
458
- logger.info("远程API正常,检测到token")
459
- try:
460
- # 使用rsync从远程同步数据
461
- result = run_command(
462
- f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",
463
- check=True
464
- )
465
- if result and result.returncode == 0:
466
- logger.info("数据同步成功")
467
- return True
468
- except Exception as e:
469
- sync_attempts += 1
470
- logger.error(f"数据同步失败: {e},尝试次数: {sync_attempts}")
471
- if sync_attempts < 3:
472
- # 重新生成SSH密钥重试
473
- generate_ssh_key()
474
  else:
475
- logger.warning(f"远程API返回数据中没有token: {response_json}")
476
-
477
  except requests.exceptions.ConnectionError as e:
478
- logger.error(f"远程API连接异常: {e},重试次数: {retry_count}")
479
- sync_attempts += 1
 
 
 
480
  except requests.exceptions.Timeout as e:
481
- logger.error(f"远程API超时: {e}")
482
  break
483
  except requests.exceptions.RequestException as e:
484
- logger.error(f"远程API请求异常: {e}")
485
  break
486
 
487
  time.sleep(5)
488
-
489
- return False
490
 
491
- def frp(configs, backstage=True):
492
- """启动FRP代理客户端"""
493
- logger.info('开始配置FRP客户端')
494
-
495
- # 杀死之前可能运行的frpc进程
496
- kill_frpc_processes()
497
-
498
- # 遍历配置启动FRP
499
- for idx, (config_data, config_file_path) in enumerate(configs):
500
- # 写入配置文件
501
- with open(config_file_path, 'w') as config_file:
502
- config_file.write(config_data)
503
-
504
- # 构建启动命令
505
- frpc_cmd = ['/content/frp/frpc', '-c', config_file_path]
506
-
507
- if backstage:
508
- # 后台运行
509
- process = subprocess.Popen(frpc_cmd)
510
- logger.info(f"FRP客户端[{idx}]已在后台启动,PID: {process.pid}")
511
- else:
512
- # 前台运行(阻塞)
513
- logger.info(f"FRP客户端[{idx}]正在前台启动")
514
- run_command(f'/content/frp/frpc -c {config_file_path}', shell=True)
515
-
516
- logger.info('所有FRP客户端已启动')
517
 
518
  def get_current_ip():
519
- """获取当前公共IP地址"""
520
- try:
521
- response = requests.get("https://ipinfo.io/ip", timeout=10)
522
- ip = response.text.strip()
523
- logger.info(f"当前公共IP: {ip}")
524
- return ip
525
- except Exception as e:
526
- logger.error(f"获取IP地址失败: {e}")
527
- return "未知"
528
 
529
  def get_geo_info(ip_address):
530
- """根据IP地址获取地理位置信息"""
531
- url = "https://api.qjqq.cn/api/Local"
532
  headers = {
533
  "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"
534
  }
535
 
536
- try:
537
- response = requests_retry_session().get(url, headers=headers, timeout=10)
 
 
538
 
539
- if response.status_code == 200:
540
- geo_info = response.json()
541
-
542
- if geo_info.get('code') == 200:
543
- data = geo_info.get('data', {})
544
- result = {
545
- 'ip': data.get('ip', "未知"),
546
- 'country': data.get('country', "未知"),
547
- 'isp': data.get('isp', "未知")
548
- }
549
- logger.info(f"获取地理信息成功: {result}")
550
- return result
551
-
552
- logger.warning(f"获取地理信息失败,状态码: {response.status_code}")
553
- return None
554
- except Exception as e:
555
- logger.error(f"获取地理信息时发生错误: {e}")
556
- return None
557
 
558
  def get_next_relay_time():
559
  """获取下一次接力时间(系统启动时间+12小时,转换为中国时区)"""
560
- try:
561
- # 获取系统启动时间
562
- boot_time = datetime.fromtimestamp(psutil.boot_time())
563
- # 设置为UTC时区
564
- utc = pytz.UTC
565
- boot_time = utc.localize(boot_time)
566
- # 转换为中国时区
567
- china_tz = pytz.timezone('Asia/Shanghai')
568
- boot_time_china = boot_time.astimezone(china_tz)
569
- # 加上12小时
570
- next_time = boot_time_china + timedelta(hours=12)
571
- return next_time.strftime("%Y-%m-%d %H:%M:%S")
572
- except Exception as e:
573
- logger.error(f"计算下次接力时间失败: {e}")
574
- return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
575
 
576
  def replace_info_in_file(file_path):
577
- """更新登录页面中的接力时间和IP信息"""
578
  try:
579
- # 检查文件是否存在
580
- if not os.path.exists(file_path):
581
- logger.error(f"文件{file_path}不存在,无法更新信息")
582
- return False
583
-
584
- # 获取当前IP地址和地理信息
585
  ip_address = get_current_ip()
586
  geo_info = get_geo_info(ip_address)
587
  next_relay_time = get_next_relay_time()
588
 
589
- if geo_info is None:
590
- logger.error("无法获取地理信息,更新文件信息失败")
591
- return False
 
592
 
593
- # 读取文件内容
594
- with open(file_path, 'r', encoding='utf-8') as file:
595
- content = file.read()
596
-
597
- # 替换接力时间
598
- time_pattern = r'接力时间\[.*?\]'
599
- time_replacement = f'接力时间[{next_relay_time}]'
600
- content = re.sub(time_pattern, time_replacement, content)
601
-
602
- # 替换IP信息
603
- ip_pattern = r'IP\[.*?\]\s*国家\s*\[.*?\]\s*IPS\[.*?\]'
604
- ip_replacement = f'IP[{geo_info["ip"]}] 国家 [{geo_info["country"]}] IPS[{geo_info["isp"]}]'
605
- content = re.sub(ip_pattern, ip_replacement, content)
606
-
607
- # 写回文件
608
- with open(file_path, 'w', encoding='utf-8') as file:
609
- file.write(content)
610
-
611
- logger.info("成功更新信息:")
612
- logger.info(f"接力时间: {next_relay_time}")
613
- logger.info(f"IP信息: IP[{geo_info['ip']}] 国家 [{geo_info['country']}] IPS[{geo_info['isp']}]")
614
- return True
615
-
616
- except Exception as e:
617
- logger.error(f"更新文件信息时发生错误: {e}")
618
- return False
619
-
620
- def update_last_uploaded_size(size):
621
- """更新上次上传的文件大小"""
622
- global last_uploaded_size
623
- last_uploaded_size = size
624
- logger.info(f"上次上传文件大小已更新为: {size} 字节")
625
-
626
- def compress_folder():
627
- """压缩SillyTavern文件夹并上传到Kaggle"""
628
- global last_uploaded_size # 声明使用全局变量
629
-
630
- # 清理并创建目录 /a
631
- if os.path.exists('/a'):
632
- run_command('rm -r /a/')
633
-
634
- os.makedirs('/a', exist_ok=True)
635
-
636
- with lock: # 使用锁防止多线程冲突
637
- # 检查文件是否已存在
638
- if os.path.exists(zip_file_path):
639
- logger.info(f"压缩文件 {zip_file_path} 已存在,跳过本次压缩")
640
- return
641
-
642
- logger.info('开始压缩数据')
643
-
644
- # 使用pigz进行多核压缩以提高效率
645
- try:
646
- result = run_command(
647
- f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
648
- shell=True,
649
- check=True,
650
- silent=True
651
- )
652
- except Exception as e:
653
- logger.error(f"压缩命令失败: {e}")
654
- return
655
-
656
- logger.info('重命名压缩后的文件')
657
- file_path = "/a/sillytavern.ctk"
658
-
659
- run_command(['mv', zip_file_path, file_path], shell=False)
660
-
661
- # 检查压缩是否成功
662
- if not os.path.exists(file_path):
663
- logger.error("压缩失败,文件不存在")
664
- return
665
-
666
- logger.info(f"数据已压缩到 {file_path}")
667
-
668
- # 获取文件大小
669
- file_size = os.path.getsize(file_path)
670
- logger.info(f'文件大小: {file_size} 字节, 上次文件大小: {last_uploaded_size} 字节')
671
-
672
- # 文件大小必须超过400MB才会上传
673
- min_size = 400 * 1024 * 1024 # 400MB
674
- if file_size < min_size:
675
- logger.info(f"文件小于{min_size/(1024*1024)}MB,不进行上传")
676
- return
677
-
678
- # 检查是否需要上传
679
- if last_uploaded_size == -1 or file_size > last_uploaded_size:
680
- # 首次运行或文件变大
681
- if last_uploaded_size == -1:
682
- logger.info("首次运行,准备上传...")
683
- else:
684
- logger.info(f"新文件 {file_path} 大于上次上传的大小,准备上传...")
685
 
686
- # 更新上传大小记录
687
- update_last_uploaded_size(file_size)
 
 
688
 
689
- # 创建元数据文件
690
- with open(metadata_file_path, 'w') as json_fid:
691
- json.dump(kaggle_metadata, json_fid)
692
 
693
- # 上传到Kaggle
694
- logger.info("开始上传到Kaggle...")
695
- os.system("kaggle datasets version -m 'new version message' -p /a")
696
- logger.info("上传完成")
697
- else:
698
- logger.info(f"新文件 {file_path} 不大于上次上传的大小,跳过上传")
699
-
700
- def repeat_task():
701
- """定期压缩和上传的后台任务"""
702
- logger.info('打包备份线程已启动')
703
- try:
704
- while True:
705
- logger.info('等待下一次打包时间...')
706
- time.sleep(18000) # 5小时执行一次
707
- compress_folder()
708
- except Exception as e:
709
- logger.error(f"打包线程异常: {e}")
710
- logger.info('打包线程已结束')
711
-
712
- def setup_tavern_environment():
713
- """设置SillyTavern运行环境"""
714
- logger.info("设置SillyTavern运行环境")
715
 
716
- try:
717
- # 切换到SillyTavern目录
718
- os.chdir(data_folder)
719
-
720
- # 安装Node.js环境
721
- run_command("nvm install node", silent=True)
722
- run_command("nvm use node", silent=True)
723
-
724
- # 安装依赖
725
- run_command("npm install -y", silent=True)
726
-
727
- # 首次运行SillyTavern
728
- try:
729
- run_command(f'yes | sh {data_folder}/start.sh', check=False, silent=True)
730
- logger.info("SillyTavern环境设置完成")
731
- return True
732
- except Exception as e:
733
- logger.error(f"首次启动SillyTavern失败: {e}")
734
- return False
735
  except Exception as e:
736
- logger.error(f"设置SillyTavern环境时出错: {e}")
737
- return False
738
 
739
- def SillyTavern():
740
- """安装和配置SillyTavern"""
741
- logger.info('开始安装SillyTavern')
742
-
743
- # 设置Kaggle凭证
744
- setup_kaggle()
745
-
746
- # 清除输出
747
- clear_output()
748
-
749
- # 清理旧文件
750
- run_command(f"rm -rf /a /sillytavern /*.zi* {data_folder}", silent=True)
751
- run_command(f"mkdir -p {data_folder}", silent=True)
752
-
753
- # 切换到根目录
754
- os.chdir('/')
755
-
756
- # 尝试从Kaggle下载
757
- download_success = download_from_kaggle()
758
-
759
- if not download_success:
760
- logger.warning("从Kaggle下载失败,尝试使用rsync同步")
761
- # 使用SSH同步备份方案
762
- generate_ssh_key()
763
- copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
764
-
765
- try:
766
- run_command(
767
- f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",
768
- check=True
769
- )
770
- logger.info("通过rsync成功同步数据")
771
- except Exception as e:
772
- logger.error(f"rsync同步失败: {e}")
773
- return False
774
- else:
775
- # 如果下载成功,解压数据
776
- extract_success = extract_tavern_data()
777
- if not extract_success:
778
- logger.error("解压SillyTavern数据失败")
779
- return False
780
-
781
- # 设置环境并启动
782
- setup_success = setup_tavern_environment()
783
- if not setup_success:
784
- logger.error("设置SillyTavern环境失败")
785
- return False
786
-
787
- # 在后台启动SillyTavern
788
- backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
789
- backup_thread.start()
790
-
791
- logger.info('SillyTavern安装和配置完成')
792
- return True
793
 
794
- # 主函���
795
- if __name__ == "__main__":
796
- # 安装SSH服务
797
- ssh()
798
-
799
- # 生成SSH密钥
800
- generate_ssh_key()
801
-
802
- # 复制SSH公钥到远程服务器
803
- copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
804
-
805
- # 配置rsync
806
- write_rsyncd_conf(data_folder)
807
-
808
- # 启动SillyTavern
809
- tavern_thread = threading.Thread(target=SillyTavern, daemon=True)
810
- tavern_thread.start()
811
- tavern_thread.join(timeout=60) # 等待最多60秒
812
-
813
- # 检查API状态
814
- api_status = check_api_status()
815
-
816
- # 如果SillyTavern已安装成功
817
- if os.path.exists(f'{data_folder}/start.sh'):
818
- # 更新登录页面信息
819
- replace_info_in_file(f'{data_folder}/public/login.html')
820
-
821
- # 启动备份线程
822
- backup_thread = threading.Thread(target=repeat_task, daemon=True)
823
- backup_thread.start()
824
-
825
- logger.info("开始配置网络连接")
826
- # 服务状态设为可用
827
- st_status = True
828
-
829
- # 启动FRP代理
830
- frp(configs, True)
831
-
832
- # 启动端口监控
833
- threading.Thread(target=monitor_port, daemon=True).start()
834
-
835
- # 监控备份线程状态
836
- while True:
837
- if backup_thread.is_alive():
838
- logger.info("备份线程正在运行...")
839
  else:
840
- logger.warning("备份线程已停止,重新启动")
841
- backup_thread = threading.Thread(target=repeat_task, daemon=True)
842
  backup_thread.start()
843
- break
844
- time.sleep(30) # 每30秒检查一次
845
-
846
- # 运行一次压缩备份
847
- compress_folder()
848
- else:
849
- logger.error(f"{data_folder} 文件夹不存在,安装失败")
850
-
851
- def setup_kaggle():
852
- """设置Kaggle API凭证"""
853
- logger.info("设置Kaggle API凭证")
854
- # 创建目录并写入kaggle.json
855
- os.makedirs("~/.kaggle", exist_ok=True)
856
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
857
  file_path = '/root/.kaggle/kaggle.json'
858
  with open(file_path, 'w') as json_file:
859
  json.dump(ini_content, json_file, indent=4)
860
-
861
- # 设置权限
862
  os.system("chmod 600 ~/.kaggle/kaggle.json")
863
- logger.info("Kaggle凭证设置完成")
864
 
865
- def download_from_kaggle():
866
- """从Kaggle下载SillyTavern数据"""
867
- logger.info(f"开始从Kaggle下载数据集 {huggingface_name}/{huggingface_Data_name}")
868
-
869
- max_attempts = 6
870
- for attempt in range(1, max_attempts + 1):
871
- logger.info(f"{attempt}次尝试下载")
872
-
 
873
  # 执行下载命令
874
- run_command(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /", silent=True)
875
-
 
876
  # 检查文件是否存在
877
  if os.path.exists(f'/{huggingface_Data_name}.zip'):
878
- logger.info(f"{huggingface_Data_name}.zip 下载成功")
879
- return True
880
-
881
- logger.warning(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
 
 
 
 
 
 
 
 
 
 
 
882
 
883
- if attempt < max_attempts:
884
- logger.info(f"等待5分钟后重试...")
885
- time.sleep(300) # 等待5分钟再重试
886
-
887
- logger.error("多次尝试下载失败")
888
- return False
 
 
 
 
 
 
 
889
 
890
- def extract_tavern_data():
891
- """解压SillyTavern数据"""
892
- logger.info("开始解压SillyTavern数据")
893
-
894
- # 检查目标文件
895
- zip_path = f'/{huggingface_Data_name}.zip'
896
- if not os.path.exists(zip_path):
897
- logger.error(f"文件 {zip_path} 不存在,无法解压")
898
- return False
899
-
900
- try:
901
- # 解压缩文件
902
- run_command(f"7z x {zip_path} -o/ -y", silent=True)
903
 
904
- # 重命名解压后的文件
905
- if os.path.exists('/sillytavern.tck'):
906
- run_command("mv /sillytavern.tck sillytavern.tar.gz")
 
 
 
 
 
 
 
 
 
 
 
 
907
 
908
- if os.path.exists('/sillytavern.ctk'):
909
- run_command("mv /sillytavern.ctk sillytavern.tar.gz")
910
 
911
- # 使用pigz解压tar.gz文件
912
- if os.path.exists('/sillytavern.tar.gz'):
913
- run_command("tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz > /dev/null", silent=True)
914
- logger.info("SillyTavern数据解压完成")
915
-
916
- # 清理下载和临时文件
917
- run_command(f"rm -r {zip_path} /sillytavern.tar.gz", silent=True)
918
- return True
919
- else:
920
- logger.error("解压后的tar.gz文件不存在")
921
- return False
922
- except Exception as e:
923
- logger.error(f"解压SillyTavern数据时出错: {e}")
924
- return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ini_content = {"username":"hdsg142saa","key":"2da57ac0c245c1ebba26017f161d5558"}
2
  frp_url = '119.8.118.149'
3
+ ssh_port = '7079'
4
  ssh_url = '43.135.135.22'
5
+ st_url = f'http://{frp_url}:7077'
6
  huggingface_name = 'hdsg142saa'
7
  huggingface_Data_name = 'qilan-st5'
8
  configs = [
 
11
  server_addr = 47.237.156.222
12
  server_port = 7000
13
 
14
+ [safsa666]
15
  type = tcp
16
  local_ip = 127.0.0.1
17
  local_port = 8000
18
+ remote_port = 7082
19
 
20
+ [sascb2f666]
21
  type = tcp
22
  local_ip = 127.0.0.1
23
  local_port = 22
24
+ remote_port = 7083
25
  """, '/content/frp/frpc.ini'),
26
  (f"""
27
  [common]
28
  server_addr = {frp_url}
29
  server_port = 7000
30
  token = qilan
31
+ [kkjmk6]
32
  type = tcp
33
  local_ip = 127.0.0.1
34
  local_port = 8000
35
  remote_port = 7076
36
  """, '/content/frp/frpc1.ini'),
37
+ # ("""
38
+ # [common]
39
+ # server_addr = 47.237.78.158
40
+ # server_port = 7000
41
+ # [kjas2]
42
+ # type = tcp
43
+ # local_ip = 127.0.0.1
44
+ # local_port = 8000
45
+ # remote_port = 7075
46
+ # """, '/content/frp/frpc2.ini'),
47
+ # ("""
48
+ # [common]
49
+ # server_addr = 45.94.69.159
50
+ # server_port = 7000
51
+ # [kja1sh5]
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 = 43.128.135.88
60
+ # server_port=7000
61
+ # [kkji1mk5]
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
+ [kkji1mk6]
72
  type=tcp
73
  local_ip=127.0.0.1
74
  local_port=22
 
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
 
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
  # 更新软件包列表
106
  def is_installed(package):
107
+ """Check if a package is installed."""
108
  try:
109
+ # Check if the package is installed using dpkg (for apt packages)
110
+ subprocess.run(['dpkg', '-s', package], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
 
111
  return True
112
+ except Exception as e:
113
  return False
114
 
115
  def install_package(package):
116
+ """Install a package using apt."""
117
+ print(f"Installing {package}...")
118
+ os.system(f"sudo apt install {package} -y > /dev/null 2>&1")
119
+ def update():
120
+ print('-----------更新软件包列表开始-------------')
121
+ # os.system("sudo apt update")
122
+ # 安装 Node.js 和 npm
123
+ # os.system("sudo apt install nodejs npm -y")
124
+ # # 全局安装 forever
125
+ # os.system("sudo npm install -g forever")
126
+ if not is_installed('nodejs'):
127
+ install_package('nodejs')
128
+
129
+ if not is_installed('npm'):
130
+ install_package('npm')
131
+ os.system("pip install -U kaggle > /dev/null 2>&1")
132
+ os.system("pip uninstall -y kaggle > /dev/null 2>&1")
133
+ os.system("pip install kaggle==1.5.6 > /dev/null 2>&1")
134
+ # os.system("apt-get install inotify-tools > /dev/null 2>&1")
135
+ os.system("pip install ruamel.yaml > /dev/null 2>&1") # install ruamel.yaml to solve the import issue
136
+ os.system("pip install pexpect > /dev/null 2>&1")
137
+ os.system("pip install pytz > /dev/null 2>&1")
138
+ os.system('pip install paramiko > /dev/null 2>&1')
139
+ os.system('apt-get install pigz -y > /dev/null 2>&1')
140
+ os.system('apt-get install pv -y > /dev/null 2>&1')
141
+ os.system("sudo apt install p7zip-full -y > /dev/null 2>&1")
142
+
143
+ print('-----------更新软件包列表结束-------------')
144
+ update()
145
+
146
+
147
+ from ruamel.yaml import YAML
148
+ clear_output(wait=True) # 清除输出
 
149
 
150
  def kill_frpc_processes():
 
151
  try:
152
+ # 使用pkill命令结束所有frpc进程
153
  subprocess.run(['pkill', '-f', 'frpc'], check=True)
154
+ print("所有frpc进程已被结束。")
155
  except subprocess.CalledProcessError as e:
156
+ # 如果pkill命令失败,打印错误信息
157
+ print(f"结束frpc进程时出错: {e}")
 
 
 
 
 
158
  kill_frpc_processes()
159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
160
 
161
  # Oneapi中转
162
  def Oneapi():
 
186
  print('-----------Oneapi中转结束-------------')
187
  # Oneapi()
188
 
189
+ # SSH
190
+ def run_command(command):
191
+ try:
192
+ subprocess.run(command, check=True, shell=True)
193
+ except subprocess.CalledProcessError as e:
194
+ print(f"An error occurred: {e}")
195
  def ssh():
196
+ print('-----------SSH开始-------------')
197
+ subprocess.run("apt update", check=True, shell=True)
198
+ subprocess.run("apt install openssh-server -y", check=True, shell=True)
199
+ subprocess.run("apt-get install vim -y", check=True, shell=True)
200
+
201
+ config_client_cmd = "sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config"
202
+ subprocess.run(config_client_cmd, check=True, shell=True)
203
+ config_server_cmd = "sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config"
204
+ subprocess.run(config_server_cmd, check=True, shell=True)
 
 
205
  run_command("systemctl restart ssh")
206
+
207
+ os.system("/etc/init.d/ssh restart")
208
+ os.system("echo 'root:qilan' | sudo chpasswd")
209
+ os.system("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
210
+ os.system("service ssh restart ")
211
+ os.system("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
212
+ print('-----------SSH结束-------------')
213
+ ssh()
214
+ clear_output()
215
+
216
+ import json
217
+ import os
218
+ import subprocess
219
+ import threading
220
+ import time
221
+
222
+ # 创建一个锁
223
+ lock = threading.Lock()
224
+ # data_folder = '/sillytavern/*'
225
+ # zip_file_path = '/a/sillytavern.zip'
226
+ data_folder = '/root/SillyTavern' # 要压缩的目录
227
+ zip_file_path = '/a/sillytavern.tar.gz' # 输出的 tar.gz 文件路径
228
+ metadata_file_path = '/a/dataset-metadata.json'
229
+ last_uploaded_size = -1
230
+
231
+ def update_last_uploaded_size(size):
232
+ global last_uploaded_size
233
+ last_uploaded_size = size
234
+
235
+ def compress_folder():
236
+ global last_uploaded_size # 声明使用全局变量
237
+
238
+ # 清理并创建目录 /a
239
+ if os.path.exists('/a'):
240
+ subprocess.run(['rm', '-r', '/a/'])
241
+
242
+ os.makedirs('/a', exist_ok=True)
243
+
244
+ with lock: # 使用锁
245
+ if os.path.exists(zip_file_path):
246
+ print(f"压缩文件 {zip_file_path} 已存在,跳过本次压缩。")
247
+ return
248
+
249
+ print('开始压缩数据')
250
+ #result = subprocess.run(['7z', 'a', '-tzip', '-mx=1','-mmt=2', zip_file_path, data_folder])
251
+ # 7z a -tzip -mx=1 -mmt=2 /a/sillytavern.zip /sillytavern/*
252
+ # tar -cvf - /sillytavern | pigz -p 6 -1 > /a/sillytavern.tar.gz
253
+ try:
254
+ result = subprocess.run(
255
+ f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
256
+ shell=True,
257
+ check=True,
258
+ stdout=subprocess.DEVNULL, # 将标准输出重定向到 /dev/null
259
+ stderr=subprocess.DEVNULL # 将标准错误也重定向到 /dev/null
260
+ )
261
+ except subprocess.CalledProcessError as e:
262
+ print(f"Command failed with return code {e.returncode}")
263
+
264
+ print('重命名压缩后的文件')
265
+ file_path = "/a/sillytavern.ctk"
266
+ print(zip_file_path)
267
+
268
+ subprocess.run(['mv', zip_file_path,file_path])
269
+ if result.returncode != 0:
270
+ print("压缩失败,请检查7z命令是否正确")
271
+ return
272
+
273
+ print(f"Data compressed into {file_path}")
274
+
275
+ file_size = os.path.getsize(file_path) # 获取压缩包的大小
276
+ print('文件大小:', file_size, '上次文件大小:', last_uploaded_size,file_size * 1024 ** 2)
277
+
278
+ # 判断是否大于800MB (800MB = 800 * 1024 * 1024 字节)
279
+ if file_size < (400 * 1024 ** 2):
280
+ print("文件小于800MB,不进行上传。")
281
+ return
282
+
283
+ if last_uploaded_size == -1 or file_size != last_uploaded_size:
284
+ # 判断是否为首次运行或上次上传大小为0
285
+ if last_uploaded_size == -1:
286
+ print("首次运行,正在执行上传...")
287
+ update_last_uploaded_size(file_size) # 更新为当前文件大小
288
+
289
+ with open(metadata_file_path, 'w') as json_fid:
290
+ json.dump(kaggle_metadata, json_fid)
291
+ os.system("kaggle datasets version -m 'new version message' -p /a")
292
+ #subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
293
+ # kaggle datasets version -m 'new version message' -p /a
294
+ last_uploaded_size = file_size
295
+
296
+ elif file_size > last_uploaded_size:
297
+ print(f"新文件 {zip_file_path} 大于上次上传的大小,正在执行上传...")
298
+ update_last_uploaded_size(file_size) # 更新元数据中的最后一次上传大小
299
+
300
+ with open(metadata_file_path, 'w') as json_fid:
301
+ json.dump(kaggle_metadata, json_fid)
302
+
303
+ subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
304
+ last_uploaded_size = file_size
305
+
306
+ else:
307
+ print(f"新文件 {zip_file_path} 不大于上次上传的大小,跳过")
308
+
309
+
310
+ def repeat_task():
311
+ print('------打包线程启动-------------')
312
+ while True:
313
+ print('等待打包')
314
+ time.sleep(18000)
315
+ compress_folder()
316
+ print('------打包线程结束-------------')
317
+
318
+
319
+ import os
320
+ import subprocess
321
+ import pexpect
322
 
323
  def generate_ssh_key():
324
+ # 生成 SSH 密钥对,并捕获输出和错误信息
 
 
325
  os.system("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub")
 
 
326
  keygen_command = "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''"
327
  try:
328
+ result = subprocess.run(keygen_command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
329
+ print("SSH key pair generated.")
330
+ print(result.stdout.decode()) # 打印标准输出信息(如成功消息)
 
 
 
 
 
 
 
 
 
331
  except subprocess.CalledProcessError as e:
332
+ print(f"Failed to generate SSH key: {e.stderr.decode() if e.stderr else e}")
 
 
333
 
334
  def copy_public_key_to_remote(host, port, user, password):
335
+ # 使用 pexpect 自动输入密码来复制公钥
 
336
  try:
337
  command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}"
338
  child = pexpect.spawn(command)
339
 
340
  # 等待密码提示并发送密码
341
+ child.expect("password:", timeout=10) # 增加超时时间
342
  child.sendline(password)
343
 
344
+ # 等待命令完成并输出结果
345
  child.expect(pexpect.EOF)
346
+
347
+ print(child.before.decode()) # 打印输出结果
348
+
349
  except Exception as e:
350
+ print(f"An error occurred: {e}")
 
351
 
 
 
 
 
 
 
 
 
 
 
 
 
352
 
353
+ # 生成 SSH 密钥对
354
+ generate_ssh_key()
355
+ os.system('chmod 600 ~/.ssh/id_rsa')
356
+ # # 复制公钥到远程服务器
357
+ copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
358
+
359
  def write_rsyncd_conf(path, port=7071):
 
360
  rsyncd_conf_content = f"""
361
  port = {port}
362
  [qilan]
 
367
  """
368
  with open('/etc/rsyncd.conf', 'w') as f:
369
  f.write(rsyncd_conf_content.strip())
370
+ print(f"Successfully wrote to /etc/rsyncd.conf for module .")
371
 
372
+ write_rsyncd_conf(data_folder)
373
+ os.system("sudo rsync --daemon")
374
+ os.system("ps aux | grep rsync")
375
 
376
  def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
377
  """创建一个带重试机制的请求会话"""
378
  session = session or requests.Session()
379
+ retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
 
 
 
 
 
 
380
  adapter = HTTPAdapter(max_retries=retry)
381
  session.mount('http://', adapter)
382
  session.mount('https://', adapter)
 
390
 
391
  import paramiko
392
 
393
+ def check_ssh_connection(host, port, username, password):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394
  try:
395
+ client = paramiko.SSHClient()
396
+ # 允许连接到不在 known_hosts 中的主机
397
+ client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
398
+ # 尝试连接
399
+ client.connect(hostname=host, port=port, username=username, password=password)
400
+ client.close()
401
+ return True
 
 
 
 
 
 
402
  except Exception as e:
403
+ print(f"SSH 连接失败: {e}")
404
+ return False
405
 
406
+
407
+
408
+
409
+ # 配置日志
410
+ logging.basicConfig(level=logging.INFO)
411
+
412
+ def check_api1():
413
+ # 第一次检查 SillyTavern 是否启动
414
+ thread_started = False
415
+ n = 0
416
+ while True:
417
+ n += 1
418
  if not os.path.exists(data_folder):
419
+ logging.error(f"/sillytavern/ 文件不存在,结束检测")
420
+ break
 
421
  try:
422
  url = "http://127.0.0.1:8000/v1"
423
+ response = requests.get(url, timeout=30)
424
+
425
  if response.status_code == 403:
426
+ print("SillyTavern已经启动")
427
  break
428
 
429
+ print("SillyTavern未启动,状态码:", response.status_code, n)
430
+
431
  except requests.exceptions.RequestException as e:
432
+ print(f"SillyTavern未启动3: {e}, 尝试次数: {n}")
433
 
 
 
 
 
434
  time.sleep(5)
435
 
436
+ print('ST本地已经运行,开始检测接口状态')
437
+ Service_status = False
438
+ n = 0
439
+ nn = 0
440
+ while True:
441
+ n += 1
442
+ if not os.path.exists(data_folder):
443
+ print(f"/sillytavern/ 文件不存在,结束检测")
444
+ break
445
+ if Service_status:
446
+ print("结束检测")
447
+ break
448
+ if nn > 2:
449
  break
 
450
  url = f"{st_url}/csrf-token"
451
  try:
452
+ response = requests_retry_session().get(url, timeout=30)
453
  response.raise_for_status()
454
  response_json = response.json()
455
+ print("%s 接口返回信息: %s", url, response_json) # 修正日志记录
 
 
456
  if "token" in response_json:
457
+ print("检测到 token")
458
+ try:
459
+ 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)
460
+ # break # 如果成功,跳出重试循环
461
+ except subprocess.CalledProcessError as e:
462
+ nn += 1
463
+ print(f"Rsync 失败,返回码: {e.returncode}, 尝试次数: {nn}")
464
+ generate_ssh_key() # 处理 SSH 密钥生成
 
 
 
 
 
 
 
 
465
  else:
466
+ print("%s 接口返回信息: %s", url, response_json) # 修正日志记录
 
467
  except requests.exceptions.ConnectionError as e:
468
+ print(f"接口异常1: {e}, 尝试次数: {n}, nn: {nn}")
469
+ # time.sleep(3)
470
+ nn += 1
471
+ if nn > 5:
472
+ break
473
  except requests.exceptions.Timeout as e:
474
+ print(f"接口异常2: {e}, 尝试次数: {n}")
475
  break
476
  except requests.exceptions.RequestException as e:
477
+ print(f"接口异常3: {e}, 尝试次数: {n}")
478
  break
479
 
480
  time.sleep(5)
 
 
481
 
482
+
483
+ def frp(configs, backstage):
484
+ print('-----------FRP开始-------------')
485
+ # 遍历所有配置并启动 FRP。
486
+ for config_data, config_file_path in configs:
487
+ with open(config_file_path, 'w') as config_file:
488
+ config_file.write(config_data)
489
+
490
+ # 启动 frpc 命令和参数。
491
+ frpc_cmd=['/content/frp/frpc', '-c', config_file_path]
492
+
493
+ if backstage:
494
+ subprocess.Popen(frpc_cmd)
495
+ else:
496
+ subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
497
+
498
+ print('-----------FRP结束-------------')
499
+
500
+ import requests
501
+ import re
502
+ from datetime import datetime, timedelta
503
+ import psutil # 用于获取系统启动时间
504
+ import pytz # 用于处理时区
 
 
 
505
 
506
  def get_current_ip():
507
+ """获取当前公共 IP 地址"""
508
+ response = requests.get("https://ipinfo.io/ip")
509
+ return response.text.strip()
 
 
 
 
 
 
510
 
511
  def get_geo_info(ip_address):
512
+ """根据 IP 地址获取地理位置信息"""
513
+ url = f"https://api.qjqq.cn/api/Local"
514
  headers = {
515
  "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"
516
  }
517
 
518
+ response = requests.get(url, headers=headers)
519
+
520
+ if response.status_code == 200:
521
+ geo_info = response.json()
522
 
523
+ if geo_info['code'] == 200:
524
+ data = geo_info['data']
525
+ return {
526
+ 'ip': data['ip'],
527
+ 'country': data['country'],
528
+ 'isp': data['isp']
529
+ }
530
+ return None
 
 
 
 
 
 
 
 
 
 
531
 
532
  def get_next_relay_time():
533
  """获取下一次接力时间(系统启动时间+12小时,转换为中国时区)"""
534
+ # 获取系统启动时间
535
+ boot_time = datetime.fromtimestamp(psutil.boot_time())
536
+ # 设置为UTC时区
537
+ utc = pytz.UTC
538
+ boot_time = utc.localize(boot_time)
539
+ # 转换为中国时区
540
+ china_tz = pytz.timezone('Asia/Shanghai')
541
+ boot_time_china = boot_time.astimezone(china_tz)
542
+ # 加上12小时
543
+ next_time = boot_time_china + timedelta(hours=12)
544
+ return next_time.strftime("%Y-%m-%d %H:%M:%S")
 
 
 
 
545
 
546
  def replace_info_in_file(file_path):
 
547
  try:
548
+ # 获取当前 IP 地址和地理信息
 
 
 
 
 
549
  ip_address = get_current_ip()
550
  geo_info = get_geo_info(ip_address)
551
  next_relay_time = get_next_relay_time()
552
 
553
+ if geo_info is not None:
554
+ # 读取文件内容
555
+ with open(file_path, 'r', encoding='utf-8') as file:
556
+ content = file.read()
557
 
558
+ # 替换接力时间
559
+ time_pattern = r'接力时间\[.*?\]'
560
+ time_replacement = f'接力时间[{next_relay_time}]'
561
+ content = re.sub(time_pattern, time_replacement, content)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
562
 
563
+ # 替换 IP 信息
564
+ ip_pattern = r'IP\[.*?\]\s*国家\s*\[.*?\]\s*IPS\[.*?\]'
565
+ ip_replacement = f'IP[{ip_address}] 国家 [{geo_info["country"]}] IPS[{geo_info["isp"]}]'
566
+ content = re.sub(ip_pattern, ip_replacement, content)
567
 
568
+ # 写回文件
569
+ with open(file_path, 'w', encoding='utf-8') as file:
570
+ file.write(content)
571
 
572
+ print(f"成功更新信息:")
573
+ print(f"接力时间: {next_relay_time}")
574
+ print(f"IP信息: IP[{ip_address}] 国家 [{geo_info['country']}] IPS[{geo_info['isp']}]")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576
  except Exception as e:
577
+ print(f"发生错误: {e}")
 
578
 
579
+ import socket
580
+ import subprocess
581
+ import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
582
 
583
+ def monitor_port():
584
+ while True:
585
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
586
+ result = sock.connect_ex(('localhost', 8000))
587
+ if result == 0:
588
+ print(f"端口 8000 正在使用中")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
589
  else:
590
+ print(f"端口 8000 未被使用")
591
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
592
  backup_thread.start()
593
+ time.sleep(5) # 每5秒检查一次
594
+ def Run_SillyTavern():
 
 
 
 
 
 
 
 
 
 
 
595
 
596
+ # subprocess.run(f'node "server.js" "$@"', shell=True, check=True)
597
+ try:
598
+ os.chdir(data_folder)
599
+ # 启动 Node.js 服务器,并将输出重定向到 /dev/null
600
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
601
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
602
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
603
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
604
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
605
+ print("已尝试启动 server.js")
606
+ except subprocess.CalledProcessError as e:
607
+ print(f"Run_SillyTavern命令失败,返回码: {e.returncode}")
608
+ except Exception as e: # 捕获所有其他异常
609
+ print(f"Run_SillyTavern发生异常: {e}")
610
+ def SillyTavern():
611
+ print('-----------SillyTavern开始-------------')
612
+ # 创建目录并写入 kaggle.json
613
+ os.system("mkdir -p ~/.kaggle")
614
  file_path = '/root/.kaggle/kaggle.json'
615
  with open(file_path, 'w') as json_file:
616
  json.dump(ini_content, json_file, indent=4)
 
 
617
  os.system("chmod 600 ~/.kaggle/kaggle.json")
 
618
 
619
+ clear_output()
620
+
621
+ os.system(f"rm -r /a /sillytavern /*.zi* {data_folder}")
622
+ os.system(f"mkdir -p {data_folder}")
623
+ os.chdir('/')
624
+ print(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
625
+ # os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
626
+ download_n = 0
627
+ while True:
628
  # 执行下载命令
629
+ if download_n > 6:
630
+ break
631
+ os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
632
  # 检查文件是否存在
633
  if os.path.exists(f'/{huggingface_Data_name}.zip'):
634
+ print(f"{huggingface_Data_name}.zip 下载成功!")
635
+ break # 跳出循环
636
+ print(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
637
+ download_n += 1
638
+ time.sleep(300) # 等待一段时间再重试(例如5秒
639
+ # os.system('kaggle datasets download xovale7506/sillytavern-data2')
640
+ # 检查文件是否存在
641
+ if not os.path.exists(f'/{huggingface_Data_name}.zip'):
642
+ print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。")
643
+ generate_ssh_key()
644
+ copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
645
+ 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)
646
+ # subprocess.run(f"rsync -avz --port=7075 ljj@{frp_url}::qilan {data_folder}/", shell=True, check=True)
647
+ # sys.exit()
648
+ else:
649
 
650
+ # 如果文件存在,可以继续执行后续代码
651
+ print(f"文件 /{huggingface_Data_name}.zip 存在,继续执行程序。")
652
+ # # 解压 sillytavern.zip
653
+ # os.system("rm *.zip")
654
+ os.system("ls /")
655
+ os.system(f"7z x /{huggingface_Data_name}.zip -o/ -y")
656
+ # os.system("mv /sillytavern.zip1 /sillytavern.zip")
657
+ # os.system("7z x /sillytavern.zip -o/sillytavern -y")
658
+ os.system("mv /sillytavern.tck sillytavern.tar.gz")
659
+ os.system("mv /sillytavern.ctk sillytavern.tar.gz")
660
+ # os.system("tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz")
661
+ os.system(f"tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz > /dev/null")
662
+ # os.system("pv /sillytavern.tar.gz | tar -xvpf - -C / --use-compress-program=pigz")
663
 
 
 
 
 
 
 
 
 
 
 
 
 
 
664
 
665
+ os.chdir(data_folder)
666
+ # os.system('git merge --abort')
667
+ # os.system('git reset --hard')
668
+ # os.system('git pull --rebase --autostash')
669
+ print('更新文件')
670
+ os.system(f"ls {data_folder}")
671
+ os.system("nvm install node")
672
+ os.system("nvm use node")
673
+ os.system("npm install -y")
674
+ try:
675
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
676
+ except subprocess.CalledProcessError as e:
677
+ print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
678
+ print("Output:", e.output)
679
+ os.system(f"ls {data_folder}")
680
 
 
 
681
 
682
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
683
+ backup_thread.start()
684
+ os.system(f"rm -r /{huggingface_Data_name}.zip /sillytavern.tar.gz")
685
+
686
+ print('-----------SillyTavern结束-------------')
687
+ threading.Thread(target=SillyTavern, daemon=True).start()
688
+ time.sleep(60)
689
+ check_api1()
690
+
691
+ if os.path.exists(f'{data_folder}/start.sh'):
692
+ replace_info_in_file(f'{data_folder}/public/login.html')
693
+ # threading.Thread(target=repeat_task, daemon=True).start() #压缩备份
694
+ # backup_thread = threading.Thread(target=repeat_task, daemon=True)
695
+ # backup_thread.start()
696
+ print("开始衔接")
697
+ Service_status = True
698
+ frp(configs, True)
699
+
700
+ threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
701
+ # while True:
702
+ # if backup_thread.is_alive():
703
+ # print("备份线程仍���运行...")
704
+ # else:
705
+ # print("备份线程已停止.")
706
+ # backup_thread = threading.Thread(target=repeat_task, daemon=True)
707
+ # backup_thread.start()
708
+ # break
709
+ # time.sleep(5)
710
+
711
+ else:
712
+ print("/sillytavern 文件不存在结束执行")
713
+ compress_folder()