Qilan2 commited on
Commit
325c653
·
verified ·
1 Parent(s): f4148d1

Update server3.py

Browse files
Files changed (1) hide show
  1. server3.py +331 -217
server3.py CHANGED
@@ -1,43 +1,38 @@
1
- ini_content = {"username":"xovale7506","key":"502e30bafc004c02aa668a279df23f3e"}
2
- frp_url = '8.219.240.86'
3
- ssh_port = '7074'
4
- st_url = f'http://{frp_url}:7073'
5
- config_data = f"""
6
- [common]
7
- server_addr = {frp_url}
8
- server_port = 7000
9
-
10
- [safgha22]
11
- type = tcp
12
- local_ip = 127.0.0.1
13
- local_port = 8000
14
- remote_port = 7073
15
- [safabf22]
16
- type = tcp
17
- local_ip = 127.0.0.1
18
- local_port = 22
19
- remote_port = {ssh_port}
20
- [saffg22]
21
- type = tcp
22
- local_ip = 127.0.0.1
23
- local_port = 3000
24
- remote_port = 7075
25
- """
26
- config_data2 = """
27
- [common]
28
- server_addr = 120.26.228.135
29
- server_port = 7000
30
-
31
- [safghac22]
32
- type = tcp
33
- local_ip = 127.0.0.1
34
- local_port = 8000
35
- remote_port = 7073
36
- """
37
-
38
  kaggle_metadata = {
39
  "title": "Your Dataset Title",
40
- "id": "xovale7506/sillytavern-data",
41
  "licenses": [{"name": "CC0-1.0"}]
42
  }
43
  st_status = True
@@ -55,27 +50,51 @@ import pexpect
55
  import glob # 导入 glob 模块
56
  from requests.adapters import HTTPAdapter
57
  from requests.packages.urllib3.util.retry import Retry
58
-
59
  os.system("rm -r /sync.sh")
60
  os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
61
-
62
  os.system("export LC_ALL=zh_CN.UTF-8")
 
 
 
63
  # 更新软件包列表
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  def update():
65
  print('-----------更新软件包列表开始-------------')
66
- os.system("sudo apt update")
67
  # 安装 Node.js 和 npm
68
- os.system("sudo apt install nodejs npm -y")
69
- # 全局安装 forever
70
- os.system("sudo npm install -g forever")
 
 
 
 
 
71
  # 安装 p7zip-full
72
  os.system("sudo apt install p7zip-full -y")
73
  os.system("pip install -U kaggle")
74
- os.system("apt-get install inotify-tools")
75
- os.system("pip install ruamel.yaml")
76
  os.system("pip install pexpect")
 
 
 
77
  print('-----------更新软件包列表结束-------------')
78
  update()
 
 
79
  from ruamel.yaml import YAML
80
  clear_output(wait=True) # 清除输出
81
 
@@ -153,8 +172,10 @@ import time
153
 
154
  # 创建一个锁
155
  lock = threading.Lock()
156
- data_folder = '/sillytavern/*'
157
- zip_file_path = '/a/sillytavern.zip'
 
 
158
  metadata_file_path = '/a/dataset-metadata.json'
159
  last_uploaded_size = -1
160
 
@@ -162,14 +183,12 @@ def update_last_uploaded_size(size):
162
  global last_uploaded_size
163
  last_uploaded_size = size
164
 
165
-
166
-
167
  def compress_folder():
168
  global last_uploaded_size # 声明使用全局变量
169
 
170
  # 清理并创建目录 /a
171
  if os.path.exists('/a'):
172
- subprocess.run(['rm', '-r', '/a'])
173
 
174
  os.makedirs('/a', exist_ok=True)
175
 
@@ -179,26 +198,40 @@ def compress_folder():
179
  return
180
 
181
  print('开始压缩数据')
182
- result = subprocess.run(['7z', 'a', '-tzip', '-mx=1','-mmt=2', zip_file_path, data_folder])
183
  # 7z a -tzip -mx=1 -mmt=2 /a/sillytavern.zip /sillytavern/*
 
 
 
 
 
 
 
 
 
 
 
 
184
  print('重命名压缩后的文件')
185
- file_path = '/a/sillytavern.zip1'
 
 
186
  subprocess.run(['mv', zip_file_path,file_path])
187
  if result.returncode != 0:
188
  print("压缩失败,请检查7z命令是否正确")
189
  return
190
-
191
  print(f"Data compressed into {file_path}")
192
 
193
  file_size = os.path.getsize(file_path) # 获取压缩包的大小
194
  print('文件大小:', file_size, '上次文件大小:', last_uploaded_size,file_size * 1024 ** 2)
195
 
196
  # 判断是否大于800MB (800MB = 800 * 1024 * 1024 字节)
197
- if file_size < (800 * 1024 ** 2):
198
  print("文件小于800MB,不进行上传。")
199
  return
200
 
201
- if last_uploaded_size == -1 or file_size > last_uploaded_size:
202
  # 判断是否为首次运行或上次上传大小为0
203
  if last_uploaded_size == -1:
204
  print("首次运行,正在执行上传...")
@@ -206,8 +239,8 @@ def compress_folder():
206
 
207
  with open(metadata_file_path, 'w') as json_fid:
208
  json.dump(kaggle_metadata, json_fid)
209
-
210
- subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
211
  # kaggle datasets version -m 'new version message' -p /a
212
  last_uploaded_size = file_size
213
 
@@ -229,7 +262,7 @@ def repeat_task():
229
  print('------打包线程启动-------------')
230
  while True:
231
  print('等待打包')
232
- time.sleep(600)
233
  compress_folder()
234
  print('------打包线程结束-------------')
235
  # repeat_task()
@@ -271,11 +304,26 @@ def copy_public_key_to_remote(host, port, user, password):
271
 
272
  # 生成 SSH 密钥对
273
  generate_ssh_key()
274
-
275
- # 复制公钥到远程服务器
276
- copy_public_key_to_remote(frp_url, ssh_port, "root", "qilan")
277
 
278
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
 
280
  def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
281
  """创建一个带重试机制的请求会话"""
@@ -286,102 +334,111 @@ def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500,
286
  session.mount('https://', adapter)
287
  return session
288
 
 
 
 
 
 
 
 
 
 
289
  def check_api1():
290
  # 第一次检查 SillyTavern 是否启动
291
- thread_started = False # 在函数内初始化标志变量
292
- n=0
293
  while True:
294
- n = n + 1
295
- if st_status == False and n > 50:
296
- print("/sillytavern 文件不存在,结束检测")
297
  break
298
  try:
299
  url = "http://127.0.0.1:8000/v1"
300
  response = requests.get(url, timeout=30)
301
 
302
- # 检查响应状态码
303
  if response.status_code == 403:
304
- print("SillyTavern已经启动")
305
- break # 接口正常,退出循环
306
 
307
- # 如果不是 403,打印其他信息
308
- print("SillyTavern未启动,状态码:", response.status_code)
309
 
310
  except requests.exceptions.RequestException as e:
311
- print(f"SillyTavern未启动3: {e}") # 打印具体错误信息
312
 
313
- time.sleep(5) # 等待5秒后重试
314
 
315
- print('开始检测接口状态')
316
  Service_status = False
317
- # 第二次检查接口状态
318
  n = 0
 
319
  while True:
320
- n = n + 1
321
- if st_status == False and n > 50:
322
- print("/sillytavern 文件不存在,结束检测")
323
  break
324
  if Service_status:
325
- print("结束检测")
326
  break
327
- url = f"{st_url}/csrf-token" # 确保这个 URL 是正确的
328
  try:
329
  response = requests_retry_session().get(url, timeout=30)
330
- response.raise_for_status() # 检查响应状态
331
- # 尝试解析 JSON 响应
332
- response_json = response.json() # 获取 JSON 内容
333
- print(url,"接口返回信息:", response_json)
334
  if "token" in response_json:
335
- print("检测到 token")
336
- # try:
337
- # subprocess.run(f"rsync -avz -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{frp_url}:/sillytavern/ /sillytavern/", shell=True, check=True)
338
- # except subprocess.CalledProcessError as e:
339
- # print(f"Rsync failed with return code: {e.returncode}")
340
- # print(f"Command output: {e.output}")
341
- # # subprocess.run(f"rsync -avz -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{frp_url}:/sillytavern/ /sillytavern/", shell=True, check=True)
342
- subprocess.run(f"sh /sync.sh -p {ssh_port} -s {frp_url}", shell=True, check=True)
343
- break # 跳出循环
 
 
 
 
 
344
  else:
345
- print("接口返回信息:", response_json)
346
-
347
  except requests.exceptions.ConnectionError as e:
348
- print(f"接口异常1: {e}")
349
- # threading.Thread(target=Frpc, daemon=True).start()
350
- break
351
-
352
  except requests.exceptions.Timeout as e:
353
- print(f"接口异常2: {e}")
354
- # threading.Thread(target=Frpc, daemon=True).start()
355
  break
356
-
357
  except requests.exceptions.RequestException as e:
358
- print(f"接口异常3: {e}")
359
- # threading.Thread(target=Frpc, daemon=True).start()
360
- break
361
 
362
- time.sleep(5) # 等待5秒后重试
363
-
364
-
365
- def frp(config_data1,config_file_path,backstage):
366
- print('-----------FRP开始-------------')
367
- '''FRP配置'''
368
- os.system("mkdir -p /content/frp")
369
- os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
370
- os.system("chmod +x /content/frp/frpc")
371
- # config_file_path = '/content/frp/frpc.ini'
372
- with open(config_file_path, 'w') as config_file:
373
- config_file.write(config_data1)
374
- # frpc 启动命令和参数
375
- frpc_cmd = ['/content/frp/frpc', '-c', config_file_path]
376
- if backstage:
377
- subprocess.Popen(frpc_cmd)
378
- else:
379
- subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
380
- print('-----------FPR结束-------------')
381
- # /content/frp/frpc -c /content/frp/frpc.ini
382
-
383
  import requests
384
  import re
 
 
 
385
 
386
  def get_current_ip():
387
  """获取当前公共 IP 地址"""
@@ -398,7 +455,7 @@ def get_geo_info(ip_address):
398
  response = requests.get(url, headers=headers)
399
 
400
  if response.status_code == 200:
401
- geo_info = response.json() # 解析为 JSON 格式
402
 
403
  if geo_info['code'] == 200:
404
  data = geo_info['data']
@@ -407,52 +464,94 @@ def get_geo_info(ip_address):
407
  'country': data['country'],
408
  'isp': data['isp']
409
  }
410
- else:
411
- print("无法获取地理位置信息")
412
- return None
413
- else:
414
- print(f"请求失败, 状态码: {response.status_code}")
415
- return None
416
-
417
- def replace_ip_and_country_in_file(file_path):
 
 
 
 
 
 
 
 
 
418
  try:
419
- # 获取当前 IP 地址
420
  ip_address = get_current_ip()
421
- print(f"获取到当前 IP: {ip_address}")
422
-
423
- # 获取地理位置信息
424
  geo_info = get_geo_info(ip_address)
 
425
 
426
  if geo_info is not None:
427
- print(f"获取到地理信息: {geo_info}")
428
-
429
  # 读取文件内容
430
  with open(file_path, 'r', encoding='utf-8') as file:
431
  content = file.read()
432
- # print(f"读取到的文件内容: {content}")
433
 
434
- # 使用正则表达式匹配 "IP[xxx]国家[yyy]" 的格式
435
- pattern = r'IP\[.*?\]国家\[.*?\]'
436
- replacement = f'机子IP[{geo_info["ip"]}]国家[{geo_info["country"]}] ISP[{geo_info["isp"]}]'
437
- new_content = re.sub(pattern, replacement, content)
438
 
439
- # print(f"替换后的内容: {new_content}")
 
 
 
440
 
441
- # 将修改后的内容写回文件
442
  with open(file_path, 'w', encoding='utf-8') as file:
443
- file.write(new_content)
444
 
445
- print(f"成功更新为: IP[{geo_info['ip']}] 国家[{geo_info['country']}] ISP[{geo_info['isp']}]")
 
 
446
 
447
- except FileNotFoundError:
448
- print(f"错误: 文件 {file_path} 不存在。")
449
- except IOError as e:
450
- print(f"IO 错误: {e}")
451
  except Exception as e:
452
- print(f"发生其他错误: {e}")
453
-
454
 
 
 
 
455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456
  def SillyTavern():
457
  print('-----------SillyTavern开始-------------')
458
  # 创建目录并写入 kaggle.json
@@ -464,68 +563,90 @@ def SillyTavern():
464
 
465
  clear_output()
466
 
467
- os.system("rm -r /a /sillytavern /*.zi* /SillyTavern/")
468
- os.system("mkdir -p /sillytavern")
469
  os.chdir('/')
470
- os.system("kaggle datasets download xovale7506/sillytavern-data")
 
 
 
 
 
 
 
 
 
 
 
 
 
471
  # 检查文件是否存在
472
- if not os.path.exists('/sillytavern-data.zip'):
473
- print(f"文件 /sillytavern-data.zip 不存在,程序将结束。")
474
- st_status = False
475
- # 如果文件存在,可以继续执行后续代码
476
- print(f"文件 /sillytavern-data.zip 存在,继续执行程序。")
 
 
 
 
 
 
477
  # # 解压 sillytavern.zip
478
- os.system("7z x /sillytavern-data.zip -o/ -y")
479
- os.system("mv /sillytavern.zip1 /sillytavern.zip")
480
- os.system("7z x /sillytavern.zip -o/sillytavern -y")
481
- os.system("rm *.zip")
482
- clear_output()
 
 
 
 
 
483
 
484
- # # 拉取最新版本
485
- # !git clone https://github.com/SillyTavern/SillyTavern.git
486
- # 强制替换掉备份
487
- # !rsync -a --delete /SillyTavern/* /sillytavern/
488
-
489
-
490
- # threading.Thread(target=Oneapi, daemon=True).start()
491
- os.chdir('/sillytavern')
492
- replace_ip_and_country_in_file('/sillytavern/public/login.html')
493
- os.system("ls")
494
- os.system("nvm install node")
495
- os.system("nvm use node")
496
- os.system("npm install -y")
497
- try:
498
- subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
499
- except subprocess.CalledProcessError as e:
500
- print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
501
- print("Output:", e.output)
502
- os.chdir('/sillytavern')
503
- subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
504
- subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
505
- subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
506
- subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True)
507
- print('-----------SillyTavern结束-------------')
508
- # os.system("yes | sh start.sh -y")
509
-
510
- # commands = [
511
- # 'yes | sh start.sh -y'
512
- # ]
513
- # run_commands(commands)
514
  threading.Thread(target=SillyTavern, daemon=True).start()
 
515
  check_api1()
516
- if not os.path.exists('/sillytavern-data.zip'):
 
 
517
  # threading.Thread(target=repeat_task, daemon=True).start() #压缩备份
518
  # backup_thread = threading.Thread(target=repeat_task, daemon=True)
519
- # backup_thread.start()
520
  print("开始衔接")
521
  Service_status = True
 
522
  # frp(config_data2,'/content/frp/frpc2.ini',True)
523
- # frp(config_data,'/content/frp/frpc.ini',False)
 
 
524
  # 以线程的形式运行 frp 任务
525
- frp_thread1 = threading.Thread(target=frp, args=(config_data2, '/content/frp/frpc2.ini', True))
526
- frp_thread1.start()
527
- frp_thread2 = threading.Thread(target=frp, args=(config_data, '/content/frp/frpc.ini', False))
528
- frp_thread2.start()
 
529
  while True:
530
  if backup_thread.is_alive():
531
  print("备份线程仍在运行...")
@@ -534,15 +655,8 @@ if not os.path.exists('/sillytavern-data.zip'):
534
  # backup_thread = threading.Thread(target=repeat_task, daemon=True)
535
  # backup_thread.start()
536
  # break
537
- try:
538
- # 检查 /sillytavern/start.sh 是否在运行
539
- subprocess.check_output(['pgrep', '-f', '/sillytavern/start.sh'])
540
- # print("脚本正在运行。")
541
- except subprocess.CalledProcessError:
542
- print("脚本未运行。退出循环。")
543
- compress_folder()
544
- break
545
  time.sleep(5)
546
 
547
  else:
548
- print("/sillytavern 文件不存在结束执行")
 
 
1
+ ini_content = {"username":"lixuhs875","key":"642ac670e3e0f7a237b53919592582c5"}
2
+ frp_url = '119.8.118.149'
3
+ ssh_port = '7072'
4
+ ssh_url = '47.74.57.131'
5
+ st_url = f'http://{frp_url}:7070'
6
+ huggingface_name = 'lixuhs875'
7
+ huggingface_Data_name = 'qilan-st1'
8
+ configs = [
9
+ ("""
10
+ [common]
11
+ server_addr = 47.237.156.222
12
+ server_port = 7000
13
+
14
+ [sasfgha]
15
+ type = tcp
16
+ local_ip = 127.0.0.1
17
+ local_port = 8000
18
+ remote_port = 7080
19
+
20
+ [sawfab2f]
21
+ type = tcp
22
+ local_ip = 127.0.0.1
23
+ local_port = 22
24
+ remote_port = 7082
25
+
26
+ [saffghg]
27
+ type = tcp
28
+ local_ip = 127.0.0.1
29
+ local_port = 8000
30
+ remote_port = 7081
31
+ """, '/content/frp/frpc.ini')
32
+ ]
 
 
 
 
 
33
  kaggle_metadata = {
34
  "title": "Your Dataset Title",
35
+ "id": f"{huggingface_name}/{huggingface_Data_name}",
36
  "licenses": [{"name": "CC0-1.0"}]
37
  }
38
  st_status = True
 
50
  import glob # 导入 glob 模块
51
  from requests.adapters import HTTPAdapter
52
  from requests.packages.urllib3.util.retry import Retry
 
53
  os.system("rm -r /sync.sh")
54
  os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
 
55
  os.system("export LC_ALL=zh_CN.UTF-8")
56
+ os.system("mkdir -p /content/frp")
57
+ os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
58
+ os.system("chmod +x /content/frp/frpc")
59
  # 更新软件包列表
60
+ def is_installed(package):
61
+ """Check if a package is installed."""
62
+ try:
63
+ # Check if the package is installed using dpkg (for apt packages)
64
+ subprocess.run(['dpkg', '-s', package], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
65
+ return True
66
+ except Exception as e:
67
+ return False
68
+
69
+ def install_package(package):
70
+ """Install a package using apt."""
71
+ print(f"Installing {package}...")
72
+ os.system(f"sudo apt install {package} -y")
73
  def update():
74
  print('-----------更新软件包列表开始-------------')
75
+ # os.system("sudo apt update")
76
  # 安装 Node.js 和 npm
77
+ # os.system("sudo apt install nodejs npm -y")
78
+ # # 全局安装 forever
79
+ # os.system("sudo npm install -g forever")
80
+ if not is_installed('nodejs'):
81
+ install_package('nodejs')
82
+
83
+ if not is_installed('npm'):
84
+ install_package('npm')
85
  # 安装 p7zip-full
86
  os.system("sudo apt install p7zip-full -y")
87
  os.system("pip install -U kaggle")
88
+ # os.system("apt-get install inotify-tools")
89
+ os.system("pip install ruamel.yaml") # install ruamel.yaml to solve the import issue
90
  os.system("pip install pexpect")
91
+ os.system("pip install pytz")
92
+ os.system('apt-get install pigz')
93
+ os.system('apt-get install pv')
94
  print('-----------更新软件包列表结束-------------')
95
  update()
96
+
97
+
98
  from ruamel.yaml import YAML
99
  clear_output(wait=True) # 清除输出
100
 
 
172
 
173
  # 创建一个锁
174
  lock = threading.Lock()
175
+ # data_folder = '/sillytavern/*'
176
+ # zip_file_path = '/a/sillytavern.zip'
177
+ data_folder = '/root/SillyTavern' # 要压缩的目录
178
+ zip_file_path = '/a/sillytavern.tar.gz' # 输出的 tar.gz 文件路径
179
  metadata_file_path = '/a/dataset-metadata.json'
180
  last_uploaded_size = -1
181
 
 
183
  global last_uploaded_size
184
  last_uploaded_size = size
185
 
 
 
186
  def compress_folder():
187
  global last_uploaded_size # 声明使用全局变量
188
 
189
  # 清理并创建目录 /a
190
  if os.path.exists('/a'):
191
+ subprocess.run(['rm', '-r', '/a/'])
192
 
193
  os.makedirs('/a', exist_ok=True)
194
 
 
198
  return
199
 
200
  print('开始压缩数据')
201
+ #result = subprocess.run(['7z', 'a', '-tzip', '-mx=1','-mmt=2', zip_file_path, data_folder])
202
  # 7z a -tzip -mx=1 -mmt=2 /a/sillytavern.zip /sillytavern/*
203
+ # tar -cvf - /sillytavern | pigz -p 6 -1 > /a/sillytavern.tar.gz
204
+ try:
205
+ result = subprocess.run(
206
+ f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
207
+ shell=True,
208
+ check=True,
209
+ stdout=subprocess.DEVNULL, # 将标准输出重定向到 /dev/null
210
+ stderr=subprocess.DEVNULL # 将标准错误也重定向到 /dev/null
211
+ )
212
+ except subprocess.CalledProcessError as e:
213
+ print(f"Command failed with return code {e.returncode}")
214
+
215
  print('重命名压缩后的文件')
216
+ file_path = "/a/sillytavern.ctk"
217
+ print(zip_file_path)
218
+
219
  subprocess.run(['mv', zip_file_path,file_path])
220
  if result.returncode != 0:
221
  print("压缩失败,请检查7z命令是否正确")
222
  return
223
+
224
  print(f"Data compressed into {file_path}")
225
 
226
  file_size = os.path.getsize(file_path) # 获取压缩包的大小
227
  print('文件大小:', file_size, '上次文件大小:', last_uploaded_size,file_size * 1024 ** 2)
228
 
229
  # 判断是否大于800MB (800MB = 800 * 1024 * 1024 字节)
230
+ if file_size < (400 * 1024 ** 2):
231
  print("文件小于800MB,不进行上传。")
232
  return
233
 
234
+ if last_uploaded_size == -1 or file_size != last_uploaded_size:
235
  # 判断是否为首次运行或上次上传大小为0
236
  if last_uploaded_size == -1:
237
  print("首次运行,正在执行上传...")
 
239
 
240
  with open(metadata_file_path, 'w') as json_fid:
241
  json.dump(kaggle_metadata, json_fid)
242
+ os.system("kaggle datasets version -m 'new version message' -p /a")
243
+ #subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
244
  # kaggle datasets version -m 'new version message' -p /a
245
  last_uploaded_size = file_size
246
 
 
262
  print('------打包线程启动-------------')
263
  while True:
264
  print('等待打包')
265
+ time.sleep(1200)
266
  compress_folder()
267
  print('------打包线程结束-------------')
268
  # repeat_task()
 
304
 
305
  # 生成 SSH 密钥对
306
  generate_ssh_key()
307
+ os.system('chmod 600 ~/.ssh/id_rsa')
308
+ # # 复制公钥到远程服务器
309
+ copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
310
 
311
+ def write_rsyncd_conf(path, port=7071):
312
+ rsyncd_conf_content = f"""
313
+ port = {port}
314
+ [qilan]
315
+ path = {path}
316
+ comment = My rsync module
317
+ read only = no
318
+ list = yes
319
+ """
320
+ with open('/etc/rsyncd.conf', 'w') as f:
321
+ f.write(rsyncd_conf_content.strip())
322
+ print(f"Successfully wrote to /etc/rsyncd.conf for module .")
323
+
324
+ write_rsyncd_conf(data_folder)
325
+ os.system("sudo rsync --daemon")
326
+ os.system("ps aux | grep rsync")
327
 
328
  def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
329
  """创建一个带重试机制的请求会话"""
 
334
  session.mount('https://', adapter)
335
  return session
336
 
337
+ import os
338
+ import time
339
+ import requests
340
+ import subprocess
341
+ import logging
342
+
343
+ # 配置日志
344
+ logging.basicConfig(level=logging.INFO)
345
+
346
  def check_api1():
347
  # 第一次检查 SillyTavern 是否启动
348
+ thread_started = False
349
+ n = 0
350
  while True:
351
+ n += 1
352
+ if not os.path.exists(data_folder):
353
+ logging.error(f"/sillytavern/ 文件不存在,结束检测")
354
  break
355
  try:
356
  url = "http://127.0.0.1:8000/v1"
357
  response = requests.get(url, timeout=30)
358
 
 
359
  if response.status_code == 403:
360
+ logging.info("SillyTavern已经启动")
361
+ break
362
 
363
+ logging.info("SillyTavern未启动,状态码:", response.status_code, n)
 
364
 
365
  except requests.exceptions.RequestException as e:
366
+ logging.error(f"SillyTavern未启动3: {e}, 尝试次数: {n}")
367
 
368
+ time.sleep(5)
369
 
370
+ logging.info('开始检测接口状态')
371
  Service_status = False
 
372
  n = 0
373
+ nn = 0
374
  while True:
375
+ n += 1
376
+ if not os.path.exists(data_folder):
377
+ logging.error(f"/sillytavern/ 文件不存在,结束检测")
378
  break
379
  if Service_status:
380
+ logging.info("结束检测")
381
  break
382
+ url = f"{st_url}/csrf-token"
383
  try:
384
  response = requests_retry_session().get(url, timeout=30)
385
+ response.raise_for_status()
386
+ response_json = response.json()
387
+ logging.info("%s 接口返回信息: %s", url, response_json) # 修正日志记录
 
388
  if "token" in response_json:
389
+ logging.info("检测到 token")
390
+ nn = 0
391
+ retry_count = 3 # 设置重试次数
392
+ for attempt in range(retry_count):
393
+ try:
394
+
395
+ subprocess.run(f"rsync -avz -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/",
396
+ shell=True, check=True, timeout=300)
397
+ break # 如果成功,跳出重试循环
398
+ except subprocess.CalledProcessError as e:
399
+ logging.error(f"Rsync 失败,返回码: {e.returncode}, 尝试次数: {attempt + 1}")
400
+ if attempt == retry_count - 1:
401
+ logging.error("所有重试均失败,停止尝试。")
402
+ generate_ssh_key() # 处理 SSH 密钥生成
403
  else:
404
+ logging.info("%s 接口返回信息: %s", url, response_json) # 修正日志记录
 
405
  except requests.exceptions.ConnectionError as e:
406
+ logging.error(f"接口异常1: {e}, 尝试次数: {n}, nn: {nn}")
407
+ nn += 1
408
+ if nn > 10:
409
+ break
410
  except requests.exceptions.Timeout as e:
411
+ logging.error(f"接口异常2: {e}, 尝试次数: {n}")
 
412
  break
 
413
  except requests.exceptions.RequestException as e:
414
+ logging.error(f"接口异常3: {e}, 尝试次数: {n}")
415
+ break
 
416
 
417
+ time.sleep(5)
418
+
419
+
420
+ def frp(configs, backstage):
421
+ print('-----------FRP开始-------------')
422
+ # 遍历所有配置并启动 FRP
423
+ for config_data, config_file_path in configs:
424
+ with open(config_file_path, 'w') as config_file:
425
+ config_file.write(config_data)
426
+
427
+ # 启动 frpc 命令和参数。
428
+ frpc_cmd=['/content/frp/frpc', '-c', config_file_path]
429
+
430
+ if backstage:
431
+ subprocess.Popen(frpc_cmd)
432
+ else:
433
+ subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
434
+
435
+ print('-----------FRP结束-------------')
436
+
 
437
  import requests
438
  import re
439
+ from datetime import datetime, timedelta
440
+ import psutil # 用于获取系统启动时间
441
+ import pytz # 用于处理时区
442
 
443
  def get_current_ip():
444
  """获取当前公共 IP 地址"""
 
455
  response = requests.get(url, headers=headers)
456
 
457
  if response.status_code == 200:
458
+ geo_info = response.json()
459
 
460
  if geo_info['code'] == 200:
461
  data = geo_info['data']
 
464
  'country': data['country'],
465
  'isp': data['isp']
466
  }
467
+ return None
468
+
469
+ def get_next_relay_time():
470
+ """获取下一次接力时间(系统启动时间+12小时,转换为中国时区)"""
471
+ # 获取系统启动时间
472
+ boot_time = datetime.fromtimestamp(psutil.boot_time())
473
+ # 设置为UTC时区
474
+ utc = pytz.UTC
475
+ boot_time = utc.localize(boot_time)
476
+ # 转换为中国时区
477
+ china_tz = pytz.timezone('Asia/Shanghai')
478
+ boot_time_china = boot_time.astimezone(china_tz)
479
+ # 加上12小时
480
+ next_time = boot_time_china + timedelta(hours=12)
481
+ return next_time.strftime("%Y-%m-%d %H:%M:%S")
482
+
483
+ def replace_info_in_file(file_path):
484
  try:
485
+ # 获取当前 IP 地址和地理信息
486
  ip_address = get_current_ip()
 
 
 
487
  geo_info = get_geo_info(ip_address)
488
+ next_relay_time = get_next_relay_time()
489
 
490
  if geo_info is not None:
 
 
491
  # 读取文件内容
492
  with open(file_path, 'r', encoding='utf-8') as file:
493
  content = file.read()
 
494
 
495
+ # 替换接力时间
496
+ time_pattern = r'接力时间\[.*?\]'
497
+ time_replacement = f'接力时间[{next_relay_time}]'
498
+ content = re.sub(time_pattern, time_replacement, content)
499
 
500
+ # 替换 IP 信息
501
+ ip_pattern = r'IP\[.*?\]\s*国家\s*\[.*?\]\s*IPS\[.*?\]'
502
+ ip_replacement = f'IP[{ip_address}] 国家 [{geo_info["country"]}] IPS[{geo_info["isp"]}]'
503
+ content = re.sub(ip_pattern, ip_replacement, content)
504
 
505
+ # 写回文件
506
  with open(file_path, 'w', encoding='utf-8') as file:
507
+ file.write(content)
508
 
509
+ print(f"成功更新信息:")
510
+ print(f"接力时间: {next_relay_time}")
511
+ print(f"IP信息: IP[{ip_address}] 国家 [{geo_info['country']}] IPS[{geo_info['isp']}]")
512
 
 
 
 
 
513
  except Exception as e:
514
+ print(f"发生错误: {e}")
 
515
 
516
+ import socket
517
+ import subprocess
518
+ import time
519
 
520
+ def monitor_port():
521
+ while True:
522
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
523
+ result = sock.connect_ex(('localhost', 8000))
524
+ if result == 0:
525
+ print(f"端口 8000 正在使用中")
526
+ else:
527
+ print(f"端口 8000 未被使用")
528
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
529
+ backup_thread.start()
530
+ # 启动脚本并在后台运行
531
+ # try:
532
+ # os.chdir(data_folder)
533
+ # process = subprocess.Popen(f'node "server.js" "$@"', shell=True)
534
+ # print(f"已尝试启动 {data_folder }/start.sh")
535
+ # # time.sleep(20)
536
+ # except Exception as e: # 捕获所有异常
537
+ # print(f"命令失败: {e}")
538
+
539
+ time.sleep(5) # 每5秒检查一次
540
+ def Run_SillyTavern():
541
+ os.chdir(data_folder)
542
+ # subprocess.run(f'node "server.js" "$@"', shell=True, check=True)
543
+ try:
544
+ # 启动 Node.js 服务器,并将输出重定向到 /dev/null
545
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
546
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
547
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
548
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
549
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
550
+ print("已尝试启动 server.js")
551
+ except subprocess.CalledProcessError as e:
552
+ print(f"命令失败,返回码: {e.returncode}")
553
+ except Exception as e: # 捕获所有其他异常
554
+ print(f"发生异常: {e}")
555
  def SillyTavern():
556
  print('-----------SillyTavern开始-------------')
557
  # 创建目录并写入 kaggle.json
 
563
 
564
  clear_output()
565
 
566
+ os.system(f"rm -r /a /sillytavern /*.zi* {data_folder}")
567
+ os.system(f"mkdir -p {data_folder}")
568
  os.chdir('/')
569
+ print(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
570
+ # os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
571
+ while True:
572
+ # 执行下载命令
573
+ os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
574
+ # 检查文件是否存在
575
+ if os.path.exists(f'/{huggingface_Data_name}.zip'):
576
+ print(f"{huggingface_Data_name}.zip 下载成功!")
577
+ break # 跳出循环
578
+
579
+ print(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
580
+
581
+ time.sleep(5) # 等待一段时间再重试(例如5秒
582
+ # os.system('kaggle datasets download xovale7506/sillytavern-data2')
583
  # 检查文件是否存在
584
+ if not os.path.exists(f'/{huggingface_Data_name}.zip'):
585
+ print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。")
586
+ generate_ssh_key()
587
+ copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
588
+ subprocess.run(f"rsync -avz -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/", shell=True, check=True)
589
+ # subprocess.run(f"rsync -avz --port=7075 ljj@{frp_url}::qilan {data_folder}/", shell=True, check=True)
590
+ # sys.exit()
591
+ else:
592
+
593
+ # 如果文件存在,可以继续执行后续代码
594
+ print(f"文件 /{huggingface_Data_name}.zip 存在,继续执行程序。")
595
  # # 解压 sillytavern.zip
596
+ # os.system("rm *.zip")
597
+ os.system("ls /")
598
+ os.system(f"7z x /{huggingface_Data_name}.zip -o/ -y")
599
+ # os.system("mv /sillytavern.zip1 /sillytavern.zip")
600
+ # os.system("7z x /sillytavern.zip -o/sillytavern -y")
601
+ os.system("mv /sillytavern.tck sillytavern.tar.gz")
602
+ os.system("mv /sillytavern.ctk sillytavern.tar.gz")
603
+ # os.system("tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz")
604
+ os.system(f"tar -xvpf /sillytavern.tar.gz -C / --use-compress-program=pigz > /dev/null")
605
+ # os.system("pv /sillytavern.tar.gz | tar -xvpf - -C / --use-compress-program=pigz")
606
 
607
+
608
+ os.chdir(data_folder)
609
+ os.system(f"ls {data_folder}")
610
+ os.system("nvm install node")
611
+ os.system("nvm use node")
612
+ os.system("npm install -y")
613
+ try:
614
+ subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
615
+ except subprocess.CalledProcessError as e:
616
+ print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.")
617
+ print("Output:", e.output)
618
+ os.system(f"ls {data_folder}")
619
+ print('更新文件')
620
+ os.system('git pull --rebase --autostash')
621
+ backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
622
+ backup_thread.start()
623
+ # subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
624
+ # subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
625
+ # subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
626
+ # subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
627
+ print('-----------SillyTavern结束-------------')
 
 
 
 
 
 
 
 
 
628
  threading.Thread(target=SillyTavern, daemon=True).start()
629
+ time.sleep(60)
630
  check_api1()
631
+ os.system("rm -r /qilan-st2.zip /sillytavern.tar.gz")
632
+ if os.path.exists(f'{data_folder}/start.sh'):
633
+ replace_info_in_file(f'{data_folder}/public/login.html')
634
  # threading.Thread(target=repeat_task, daemon=True).start() #压缩备份
635
  # backup_thread = threading.Thread(target=repeat_task, daemon=True)
636
+ backup_thread.start()
637
  print("开始衔接")
638
  Service_status = True
639
+ frp(configs, True)
640
  # frp(config_data2,'/content/frp/frpc2.ini',True)
641
+ # frp(config_data,'/content/frp/frpc.ini',True)
642
+ # frp(config_data3,'/content/frp/frpc3.ini',True)
643
+ # frp(config_data4,'/content/frp/frpc4.ini',True)
644
  # 以线程的形式运行 frp 任务
645
+ # frp_thread1 = threading.Thread(target=frp, args=(config_data2, '/content/frp/frpc2.ini', True))
646
+ # frp_thread1.start()
647
+ # frp_thread2 = threading.Thread(target=frp, args=(config_data, '/content/frp/frpc.ini', False))
648
+ # frp_thread2.start()
649
+ threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
650
  while True:
651
  if backup_thread.is_alive():
652
  print("备份线程仍在运行...")
 
655
  # backup_thread = threading.Thread(target=repeat_task, daemon=True)
656
  # backup_thread.start()
657
  # break
 
 
 
 
 
 
 
 
658
  time.sleep(5)
659
 
660
  else:
661
+ print("/sillytavern 文件不存在结束执行")
662
+ compress_folder()