Qilan2 commited on
Commit
bd0c43e
·
verified ·
1 Parent(s): 401788a

Update server5.py

Browse files
Files changed (1) hide show
  1. server5.py +534 -225
server5.py CHANGED
@@ -104,55 +104,136 @@ os.system("chmod +x /content/frp/frpc")
104
 
105
  # 更新软件包列表
106
  def is_installed(package):
107
- """检查软件包是否已安装"""
108
  try:
 
109
  subprocess.run(['dpkg', '-s', package], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
110
  return True
111
- except Exception:
112
  return False
113
 
114
  def install_package(package):
115
- """使用apt安装软件包"""
116
- print(f"正在安装 {package}...")
117
- os.system(f"sudo apt install {package} -y > /dev/null 2>&1")
118
-
119
  def update():
120
  print('-----------更新软件包列表开始-------------')
 
 
 
 
 
 
 
121
 
122
- # 安装必要的软件包
123
- packages = {
124
- 'nodejs': '安装Node.js',
125
- 'npm': '安装npm',
126
- 'p7zip-full': '安装7zip',
127
- 'pigz': '安装pigz压缩工具',
128
- 'pv': '安装pv工具',
129
- 'openssh-server': '安装SSH服务器'
130
- }
131
-
132
- for package, description in packages.items():
133
- if not is_installed(package):
134
- print(description)
135
- install_package(package)
136
-
137
- # 安装Python包
138
- python_packages = [
139
- 'kaggle==1.5.6',
140
- 'ruamel.yaml',
141
- 'pexpect',
142
- 'pytz',
143
- 'paramiko'
144
- ]
145
-
146
- for package in python_packages:
147
- os.system(f"pip install {package} > /dev/null 2>&1")
148
-
149
  print('-----------更新软件包列表结束-------------')
 
150
 
151
- # ... 其他函数保持不变 ...
152
 
153
- def compress_folder():
154
- """压缩SillyTavern文件夹并上传到Kaggle"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  global last_uploaded_size
 
 
 
 
156
 
157
  # 清理并创建目录 /a
158
  if os.path.exists('/a'):
@@ -160,109 +241,372 @@ def compress_folder():
160
 
161
  os.makedirs('/a', exist_ok=True)
162
 
163
- with lock:
164
  if os.path.exists(zip_file_path):
165
  print(f"压缩文件 {zip_file_path} 已存在,跳过本次压缩。")
166
  return
167
 
168
  print('开始压缩数据')
 
 
 
169
  try:
170
- # 使用pigz进行多线程压缩,提高效率
171
  result = subprocess.run(
172
- f'tar -cf - {data_folder} | pigz -p 4 -1 > {zip_file_path} 2> /dev/null',
173
- shell=True,
174
- check=True,
175
- stdout=subprocess.DEVNULL,
176
- stderr=subprocess.DEVNULL
177
  )
178
- print('压缩完成')
179
  except subprocess.CalledProcessError as e:
180
- print(f"压缩命令失败,返回码: {e.returncode}")
181
- return
182
 
183
  print('重命名压缩后的文件')
184
  file_path = "/a/sillytavern.ctk"
185
- subprocess.run(['mv', zip_file_path, file_path])
 
 
 
 
 
186
 
187
- print(f"数据已压缩到 {file_path}")
188
 
189
- file_size = os.path.getsize(file_path)
190
- print(f'文件大小: {file_size/1024/1024:.2f}MB, 上次文件大小: {last_uploaded_size/1024/1024:.2f}MB 如果上次为-1')
191
 
192
- # 判断是否大于400MB
193
- if file_size < (400 * 1024 * 1024):
194
- print("文件小于400MB,不进行上传。")
195
  return
196
 
197
- # 上传逻辑优化
198
- should_upload = (last_uploaded_size == -1) or (file_size > last_uploaded_size * 1.05)
199
-
200
- if should_upload:
201
- print(f"{'首次上传' if last_uploaded_size == -1 else '文件大小显著增加'},正在执行上传...")
202
- update_last_uploaded_size(file_size)
203
-
204
- with open(metadata_file_path, 'w') as json_fid:
205
- json.dump(kaggle_metadata, json_fid)
206
-
207
- try:
208
- upload_result = subprocess.run(
209
- ['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'],
210
- check=True,
211
- stdout=subprocess.PIPE,
212
- stderr=subprocess.PIPE
213
- )
214
- print("上传成功:", upload_result.stdout.decode())
215
- except subprocess.CalledProcessError as e:
216
- print(f"上传失败: {e.stderr.decode() if e.stderr else e}")
 
 
 
217
  else:
218
- print(f"新文件大小变化不显著,跳过上传")
219
 
220
- # 改进SSH密钥管理
221
- def setup_ssh():
222
- """设置SSH服务和密钥"""
223
- print('-----------SSH配置开始-------------')
224
-
225
- # 安装和配置SSH服务器
226
- subprocess.run("apt update", check=True, shell=True)
227
- subprocess.run("apt install openssh-server -y", check=True, shell=True)
228
-
229
- # 配置SSH允许root登录
230
- config_commands = [
231
- "sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config",
232
- "sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config",
233
- "echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config",
234
- "echo 'root:qilan' | sudo chpasswd",
235
- "systemctl restart ssh",
236
- "/etc/init.d/ssh restart",
237
- "service ssh restart"
238
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
 
240
- for cmd in config_commands:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  try:
242
- subprocess.run(cmd, shell=True, check=True)
243
- except subprocess.CalledProcessError as e:
244
- print(f"SSH配置命令失败: {cmd}, 错误: {e}")
245
-
246
- # 生成SSH密钥
247
- generate_ssh_key()
248
- os.system('chmod 600 ~/.ssh/id_rsa')
 
 
 
 
 
 
249
 
250
- # 尝试复制公钥到远程服务器
251
- max_attempts = 3
252
- for attempt in range(max_attempts):
 
 
 
 
 
 
 
 
 
 
 
 
253
  try:
254
- copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
255
- print(f"SSH密钥复制成功 (尝试 {attempt+1}/{max_attempts})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  break
257
- except Exception as e:
258
- print(f"SSH密钥复制失败 (尝试 {attempt+1}/{max_attempts}): {e}")
259
- if attempt < max_attempts - 1:
260
- print("5秒后重试...")
261
- time.sleep(5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
263
- print('-----------SSH配置结束-------------')
 
 
 
 
 
 
 
 
 
 
264
 
265
- # 改进SillyTavern下载和安装
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
266
  def SillyTavern():
267
  print('-----------SillyTavern开始-------------')
268
  # 创建目录并写入 kaggle.json
@@ -274,131 +618,96 @@ def SillyTavern():
274
 
275
  clear_output()
276
 
277
- # 清理旧文件并创建目录
278
- os.system(f"rm -rf /a /sillytavern /*.zi* {data_folder}")
279
  os.system(f"mkdir -p {data_folder}")
280
  os.chdir('/')
281
-
282
- # 下载数据集,带重试机制
283
- print(f"正在下载数据集: {huggingface_name}/{huggingface_Data_name}")
284
- download_success = False
285
- max_attempts = 6
286
-
287
- for attempt in range(max_attempts):
288
- print(f"下载尝试 {attempt+1}/{max_attempts}")
289
  os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
290
-
291
  if os.path.exists(f'/{huggingface_Data_name}.zip'):
292
- file_size = os.path.getsize(f'/{huggingface_Data_name}.zip')
293
- print(f"{huggingface_Data_name}.zip 下载成功!文件大小: {file_size/1024/1024:.2f}MB")
294
- download_success = True
295
- break
296
-
297
- print(f"下载失败,5分钟后重试...")
298
- time.sleep(300)
299
-
300
- # 如果下载失败,尝试使用rsync同步
301
- if not download_success:
302
- print(f"下载失败,尝试使用rsync从远程服务器同步")
303
- try:
304
- setup_ssh() # 确保SSH配置正确
305
- rsync_cmd = f"rsync -avz --timeout=600 -e 'ssh -p {ssh_port} -o StrictHostKeyChecking=no' root@{ssh_url}:{data_folder}/ {data_folder}/"
306
- print(f"执行同步命令: {rsync_cmd}")
307
- subprocess.run(rsync_cmd, shell=True, check=True)
308
- print("同步完成")
309
- except subprocess.CalledProcessError as e:
310
- print(f"同步失败: {e}")
311
  else:
312
- # 解压文件
313
- print("开始解压文件...")
314
- try:
315
- # 处理不同可能的文件名
316
- if os.path.exists(f'/{huggingface_Data_name}.zip'):
317
- os.system(f"7z x /{huggingface_Data_name}.zip -o/ -y > /dev/null")
318
-
319
- # 处理可能的文件名变体
320
- for possible_file in ['/sillytavern.tck', '/sillytavern.ctk']:
321
- if os.path.exists(possible_file):
322
- os.system(f"mv {possible_file} /sillytavern.tar.gz")
323
-
324
- # 解压tar.gz文件
325
- if os.path.exists('/sillytavern.tar.gz'):
326
- os.system(f"tar -xf /sillytavern.tar.gz -C / --use-compress-program=pigz > /dev/null")
327
- print("解压完成")
328
- except Exception as e:
329
- print(f"解压过程中出错: {e}")
330
-
331
- # 安装和启动SillyTavern
332
- if os.path.exists(f'{data_folder}'):
333
- os.chdir(data_folder)
334
- print('更新SillyTavern...')
335
 
336
- # 安装Node.js依赖
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
337
  os.system("nvm install node")
338
  os.system("nvm use node")
339
  os.system("npm install -y")
340
-
341
- # 启动SillyTavern
342
  try:
343
- print("启动SillyTavern...")
344
  subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, check=True)
345
  except subprocess.CalledProcessError as e:
346
- print(f"启动失败: {e}")
 
 
347
 
348
- # 清理下载的文件
349
- os.system(f"rm -rf /{huggingface_Data_name}.zip /sillytavern.tar.gz")
350
- else:
351
- print(f"错误: {data_folder}目录不存在")
352
-
353
- print('-----------SillyTavern结束-------------')
354
-
355
- # 主程序逻辑优化
356
- def main():
357
- # 初始化
358
- update()
359
- kill_frpc_processes()
360
- setup_ssh()
361
-
362
- # 启动SillyTavern
363
- st_thread = threading.Thread(target=SillyTavern, daemon=True)
364
- st_thread.start()
365
-
366
- # 等待SillyTavern启动
367
- print("等待SillyTavern启动...")
368
- time.sleep(60)
369
- check_api1()
370
-
371
- # 如果SillyTavern已启动,开始其他服务
372
- if os.path.exists(f'{data_folder}/start.sh'):
373
- # 更新登录页面信息
374
- replace_info_in_file(f'{data_folder}/public/login.html')
375
 
376
- # 启动备份线程
377
- print("启动备份线程...")
378
- backup_thread = threading.Thread(target=repeat_task, daemon=True)
379
  backup_thread.start()
380
-
381
- # 启动FRP
382
- print("启动FRP服务...")
383
- Service_status = True
384
- frp(configs, True)
385
-
386
- # 启动端口监控
387
- threading.Thread(target=monitor_port, daemon=True).start()
388
-
389
- # 监控备份线程
390
- while True:
391
- if backup_thread.is_alive():
392
- print("备份线程运行中...")
393
- else:
394
- print("备份线程已停止,重新启动...")
395
- backup_thread = threading.Thread(target=repeat_task, daemon=True)
396
- backup_thread.start()
397
- time.sleep(300) # 每5分钟检查一次
398
- else:
399
- print(f"错误: {data_folder}/start.sh 不存在,无法继续执行")
400
- compress_folder()
 
 
 
 
 
401
 
402
- # 如果直接运行脚本,执行main函数
403
- if __name__ == "__main__":
404
- main()
 
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():
163
+ print('-----------Oneapi中转开始-------------')
164
+ # 删除旧的 one-api 文件夹(如果存在)
165
+ os.system("rm -rf /one/one-api") # 使用 -f 参数以避免错误
166
+ os.system("mkdir -p /one") # 创建目录
167
+ # 下载 one-api 文件
168
+ url = "https://github.com/songquanpeng/one-api/releases/download/v0.6.8/one-api"
169
+ os.system(f"wget {url} -O /one/one-api") # 正确下载并重命名为 /one/one-api
170
+ # 修改文件权限,使其可执行
171
+ os.system("chmod +x /one/one-api")
172
+ # 设置环境变量
173
+ os.environ["THEME"] = "berry"
174
+ os.environ["TIKTOKEN_CACHE_DIR"] = os.getcwd() # 使用Python的os.getcwd()获取当前工作目录
175
+ # 设置MySQL数据库的环境变量
176
+ db_user = "oneapi"
177
+ db_password = "epBjK5ZKysCe6yr3"
178
+ db_host = "106.52.51.116"
179
+ db_port = "3306"
180
+ db_name = "oneapi"
181
+ dsn = f"{db_user}:{db_password}@tcp({db_host}:{db_port})/{db_name}"
182
+ os.environ["SQL_DSN"] = dsn
183
+ command = ['/one/one-api', '--port', '3000']
184
+ process = subprocess.Popen(command) # 启动程序并将其放到后台执行
185
+ print(f"OneAPI程序已在后台启动,进程ID为:{process.pid}")
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'):
 
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]
363
+ path = {path}
364
+ comment = My rsync module
365
+ read only = no
366
+ list = yes
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)
383
+ return session
384
+
385
+ import os
386
+ import time
387
+ import requests
388
+ import subprocess
389
+ import logging
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
 
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()