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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ini_content = {"username":"ighlnvd551","key":"14dee8c2e790b386ca7a61e974537d66"}
|
| 2 |
+
frp_url = '119.8.118.149'
|
| 3 |
+
ssh_port = '7081'
|
| 4 |
+
ssh_url = '43.129.165.236'
|
| 5 |
+
st_url = f'http://{frp_url}:7079'
|
| 6 |
+
huggingface_name = 'rachelamnao'
|
| 7 |
+
huggingface_Data_name = 'card-hub'
|
| 8 |
+
configs = [
|
| 9 |
+
("""
|
| 10 |
+
[common]
|
| 11 |
+
server_addr = 47.237.156.222
|
| 12 |
+
server_port = 7000
|
| 13 |
+
|
| 14 |
+
[safsa77]
|
| 15 |
+
type = tcp
|
| 16 |
+
local_ip = 127.0.0.1
|
| 17 |
+
local_port = 8000
|
| 18 |
+
remote_port = 7084
|
| 19 |
+
|
| 20 |
+
[sascb2f77]
|
| 21 |
+
type = tcp
|
| 22 |
+
local_ip = 127.0.0.1
|
| 23 |
+
local_port = 22
|
| 24 |
+
remote_port = 7085
|
| 25 |
+
""", '/content/frp/frpc.ini'),
|
| 26 |
+
(f"""
|
| 27 |
+
[common]
|
| 28 |
+
server_addr = {frp_url}
|
| 29 |
+
server_port = 7000
|
| 30 |
+
token = qilan
|
| 31 |
+
[1kkjmk7]
|
| 32 |
+
type = tcp
|
| 33 |
+
local_ip = 127.0.0.1
|
| 34 |
+
local_port = 8000
|
| 35 |
+
remote_port = 7078
|
| 36 |
+
""", '/content/frp/frpc1.ini'),
|
| 37 |
+
("""
|
| 38 |
+
[common]
|
| 39 |
+
server_addr = 124.156.207.7
|
| 40 |
+
server_port = 7000
|
| 41 |
+
[2kjas7]
|
| 42 |
+
type = tcp
|
| 43 |
+
local_ip = 127.0.0.1
|
| 44 |
+
local_port = 8000
|
| 45 |
+
remote_port = 7077
|
| 46 |
+
""", '/content/frp/frpc2.ini'),
|
| 47 |
+
("""
|
| 48 |
+
[common]
|
| 49 |
+
server_addr = 8.217.51.145
|
| 50 |
+
server_port = 7000
|
| 51 |
+
[3kja1sh7]
|
| 52 |
+
type = tcp
|
| 53 |
+
local_ip = 127.0.0.1
|
| 54 |
+
local_port = 8000
|
| 55 |
+
remote_port = 7077
|
| 56 |
+
""", '/content/frp/frpc3.ini'),
|
| 57 |
+
("""
|
| 58 |
+
[common]
|
| 59 |
+
server_addr = 8.210.221.90
|
| 60 |
+
server_port=7000
|
| 61 |
+
[4kkji1mk7]
|
| 62 |
+
type=tcp
|
| 63 |
+
local_ip=127.0.0.1
|
| 64 |
+
local_port=8000
|
| 65 |
+
remote_port=7077
|
| 66 |
+
""", '/content/frp/frpc4.ini'),
|
| 67 |
+
(f"""
|
| 68 |
+
[common]
|
| 69 |
+
server_addr = {ssh_url}
|
| 70 |
+
server_port=7000
|
| 71 |
+
[5kkji1mk7]
|
| 72 |
+
type=tcp
|
| 73 |
+
local_ip=127.0.0.1
|
| 74 |
+
local_port=22
|
| 75 |
+
remote_port={ssh_port}
|
| 76 |
+
""", '/content/frp/frpc5.ini')
|
| 77 |
+
]
|
| 78 |
+
kaggle_metadata = {
|
| 79 |
+
"title": "Your Dataset Title",
|
| 80 |
+
"id": f"{huggingface_name}/{huggingface_Data_name}",
|
| 81 |
+
"licenses": [{"name": "CC0-1.0"}]
|
| 82 |
+
}
|
| 83 |
+
st_status = True
|
| 84 |
+
import subprocess
|
| 85 |
+
import os
|
| 86 |
+
import sys
|
| 87 |
+
import configparser
|
| 88 |
+
from IPython.display import clear_output
|
| 89 |
+
import urllib.request
|
| 90 |
+
from pathlib import Path
|
| 91 |
+
import requests
|
| 92 |
+
import json
|
| 93 |
+
import threading
|
| 94 |
+
import time
|
| 95 |
+
import pexpect
|
| 96 |
+
import socket
|
| 97 |
+
import time
|
| 98 |
+
import glob # 导入 glob 模块
|
| 99 |
+
from requests.adapters import HTTPAdapter
|
| 100 |
+
from requests.packages.urllib3.util.retry import Retry
|
| 101 |
+
os.system("export LC_ALL=zh_CN.UTF-8")
|
| 102 |
+
# 创建 FRP 文件夹并下载 frpc 可执行文件。
|
| 103 |
+
os.system("mkdir -p /content/frp")
|
| 104 |
+
os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
|
| 105 |
+
os.system("chmod +x /content/frp/frpc")
|
| 106 |
+
# 更新软件包列表
|
| 107 |
+
def is_installed(package):
|
| 108 |
+
"""Check if a package is installed."""
|
| 109 |
+
try:
|
| 110 |
+
# Check if the package is installed using dpkg (for apt packages)
|
| 111 |
+
subprocess.run(['dpkg', '-s', package], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 112 |
+
return True
|
| 113 |
+
except Exception as e:
|
| 114 |
+
return False
|
| 115 |
+
|
| 116 |
+
def install_package(package):
|
| 117 |
+
"""Install a package using apt."""
|
| 118 |
+
print(f"Installing {package}...")
|
| 119 |
+
os.system(f"sudo apt install {package} -y")
|
| 120 |
+
def update():
|
| 121 |
+
print('-----------更新软件包列表开始-------------')
|
| 122 |
+
# os.system("sudo apt update")
|
| 123 |
+
# 安装 Node.js 和 npm
|
| 124 |
+
# os.system("sudo apt install nodejs npm -y")
|
| 125 |
+
# # 全局安装 forever
|
| 126 |
+
# os.system("sudo npm install -g forever")
|
| 127 |
+
if not is_installed('nodejs'):
|
| 128 |
+
install_package('nodejs')
|
| 129 |
+
|
| 130 |
+
if not is_installed('npm'):
|
| 131 |
+
install_package('npm')
|
| 132 |
+
# 安装 p7zip-full
|
| 133 |
+
os.system("sudo apt install p7zip-full -y")
|
| 134 |
+
os.system("pip install -U kaggle")
|
| 135 |
+
os.system("pip uninstall -y kaggle > /dev/null 2>&1")
|
| 136 |
+
os.system("pip install kaggle==1.5.6 > /dev/null 2>&1")
|
| 137 |
+
# os.system("apt-get install inotify-tools")
|
| 138 |
+
os.system("pip install ruamel.yaml") # install ruamel.yaml to solve the import issue
|
| 139 |
+
os.system("pip install pexpect")
|
| 140 |
+
os.system("pip install pytz")
|
| 141 |
+
os.system('apt-get install pigz')
|
| 142 |
+
os.system('apt-get install pv')
|
| 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 |
+
# SSH
|
| 162 |
+
def run_command(command):
|
| 163 |
+
try:
|
| 164 |
+
subprocess.run(command, check=True, shell=True)
|
| 165 |
+
except subprocess.CalledProcessError as e:
|
| 166 |
+
print(f"An error occurred: {e}")
|
| 167 |
+
def ssh():
|
| 168 |
+
print('-----------SSH开始-------------')
|
| 169 |
+
subprocess.run("apt update", check=True, shell=True)
|
| 170 |
+
subprocess.run("apt install openssh-server -y", check=True, shell=True)
|
| 171 |
+
subprocess.run("apt-get install vim -y", check=True, shell=True)
|
| 172 |
+
|
| 173 |
+
config_client_cmd = "sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config"
|
| 174 |
+
subprocess.run(config_client_cmd, check=True, shell=True)
|
| 175 |
+
config_server_cmd = "sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config"
|
| 176 |
+
subprocess.run(config_server_cmd, check=True, shell=True)
|
| 177 |
+
run_command("systemctl restart ssh")
|
| 178 |
+
|
| 179 |
+
os.system("/etc/init.d/ssh restart")
|
| 180 |
+
os.system("echo 'root:qilan' | sudo chpasswd")
|
| 181 |
+
os.system("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
|
| 182 |
+
os.system("service ssh restart ")
|
| 183 |
+
os.system("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ")
|
| 184 |
+
print('-----------SSH结束-------------')
|
| 185 |
+
ssh()
|
| 186 |
+
clear_output()
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# 创建一个锁
|
| 191 |
+
lock = threading.Lock()
|
| 192 |
+
data_folder = '/Card_Hub' # 要压缩的目录
|
| 193 |
+
zip_file_path = '/a/Card_Hub.tar.gz' # 输出的 tar.gz 文件路径
|
| 194 |
+
metadata_file_path = '/a/dataset-metadata.json'
|
| 195 |
+
last_uploaded_size = -1
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def update_last_uploaded_size(size):
|
| 199 |
+
global last_uploaded_size
|
| 200 |
+
last_uploaded_size = size
|
| 201 |
+
|
| 202 |
+
def get_folder_size(folder):
|
| 203 |
+
"""使用 du 命令获取文件夹的总大小(字节数)"""
|
| 204 |
+
result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 205 |
+
if result.returncode == 0:
|
| 206 |
+
size = result.stdout.split()[0] # 获取大小
|
| 207 |
+
return int(size)
|
| 208 |
+
else:
|
| 209 |
+
print(f"Error calculating size: {result.stderr.decode()}")
|
| 210 |
+
return 0
|
| 211 |
+
|
| 212 |
+
def compress_folder():
|
| 213 |
+
global last_uploaded_size # 声明使用全局变量
|
| 214 |
+
# 清理并创建目录 /a
|
| 215 |
+
if os.path.exists('/a'):
|
| 216 |
+
subprocess.run(['rm', '-r', '/a/'])
|
| 217 |
+
os.makedirs('/a', exist_ok=True)
|
| 218 |
+
with lock: # 使用锁
|
| 219 |
+
# 获取当前文件夹的大小
|
| 220 |
+
current_folder_size = get_folder_size(data_folder)
|
| 221 |
+
print(f"当前文件夹大小: {current_folder_size} 字节")
|
| 222 |
+
|
| 223 |
+
# 判断文件夹大小是否大于 800MB (800MB = 800 * 1024 * 1024 字节)
|
| 224 |
+
if current_folder_size < (100 * 1024 ** 2):
|
| 225 |
+
print("文件夹小于800MB,不进行上传和压缩。")
|
| 226 |
+
return
|
| 227 |
+
|
| 228 |
+
# 如果是首次运行或者文件夹大小不同于上次上传,进行压缩
|
| 229 |
+
if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
|
| 230 |
+
print('开始压缩数据')
|
| 231 |
+
try:
|
| 232 |
+
# 执行压缩
|
| 233 |
+
result = subprocess.run(
|
| 234 |
+
f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path} 2> /dev/null',
|
| 235 |
+
shell=True,
|
| 236 |
+
check=True,
|
| 237 |
+
stdout=subprocess.DEVNULL, # 将标准输出重定向到 /dev/null
|
| 238 |
+
stderr=subprocess.DEVNULL # 将标准错误也重定向到 /dev/null
|
| 239 |
+
)
|
| 240 |
+
except subprocess.CalledProcessError as e:
|
| 241 |
+
print(f"命令失败,返回代码: {e.returncode}")
|
| 242 |
+
return
|
| 243 |
+
|
| 244 |
+
print('压缩完成')
|
| 245 |
+
file_path = "/a/Card_Hub.ctk"
|
| 246 |
+
subprocess.run(['mv', zip_file_path, file_path])
|
| 247 |
+
print(f"数据压缩为 {file_path}")
|
| 248 |
+
|
| 249 |
+
file_size = os.path.getsize(file_path) # 获取压缩包的大小
|
| 250 |
+
print('文件大小:', file_size)
|
| 251 |
+
|
| 252 |
+
if file_size < (100 * 1024 ** 2): # 判断压缩后的大小是否小于 800MB
|
| 253 |
+
print("压缩文件小于800MB,不进行上传。")
|
| 254 |
+
return
|
| 255 |
+
|
| 256 |
+
# 执行上传
|
| 257 |
+
if last_uploaded_size == -1:
|
| 258 |
+
print("首次运行,正在执行上传...")
|
| 259 |
+
update_last_uploaded_size(file_size)
|
| 260 |
+
|
| 261 |
+
with open(metadata_file_path, 'w') as json_fid:
|
| 262 |
+
json.dump(kaggle_metadata, json_fid)
|
| 263 |
+
|
| 264 |
+
subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
|
| 265 |
+
last_uploaded_size = file_size
|
| 266 |
+
else:
|
| 267 |
+
print(f"新文件大小 {file_size} 大于上次上传的大小,正在执行上传...")
|
| 268 |
+
update_last_uploaded_size(file_size)
|
| 269 |
+
|
| 270 |
+
with open(metadata_file_path, 'w') as json_fid:
|
| 271 |
+
json.dump(kaggle_metadata, json_fid)
|
| 272 |
+
|
| 273 |
+
subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a'])
|
| 274 |
+
last_uploaded_size = file_size
|
| 275 |
+
|
| 276 |
+
else:
|
| 277 |
+
print(f"新文件夹大小 {current_folder_size} 不大于上次上传的大小,跳过")
|
| 278 |
+
|
| 279 |
+
def repeat_task():
|
| 280 |
+
print('------打包线程启动-------------')
|
| 281 |
+
while True:
|
| 282 |
+
print('等待打包')
|
| 283 |
+
time.sleep(18000)
|
| 284 |
+
compress_folder()
|
| 285 |
+
print('------打包线程结束-------------')
|
| 286 |
+
# repeat_task()
|
| 287 |
+
# compress_folder()
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def generate_ssh_key():
|
| 292 |
+
# 生成 SSH 密钥对,并捕获输出和错误信息
|
| 293 |
+
os.system("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub")
|
| 294 |
+
keygen_command = "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''"
|
| 295 |
+
try:
|
| 296 |
+
result = subprocess.run(keygen_command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 297 |
+
print("SSH key pair generated.")
|
| 298 |
+
print(result.stdout.decode()) # 打印标准输出信息(如成功消息)
|
| 299 |
+
except subprocess.CalledProcessError as e:
|
| 300 |
+
print(f"Failed to generate SSH key: {e.stderr.decode() if e.stderr else e}")
|
| 301 |
+
|
| 302 |
+
def copy_public_key_to_remote(host, port, user, password):
|
| 303 |
+
# 使用 pexpect 自动输入密码来复制公钥
|
| 304 |
+
try:
|
| 305 |
+
command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}"
|
| 306 |
+
child = pexpect.spawn(command)
|
| 307 |
+
|
| 308 |
+
# 等待密码提示并发送密码
|
| 309 |
+
child.expect("password:", timeout=10) # 增加超时时间
|
| 310 |
+
child.sendline(password)
|
| 311 |
+
|
| 312 |
+
# 等待命令完成并输出结果
|
| 313 |
+
child.expect(pexpect.EOF)
|
| 314 |
+
|
| 315 |
+
print(child.before.decode()) # 打印输出结果
|
| 316 |
+
|
| 317 |
+
except Exception as e:
|
| 318 |
+
print(f"An error occurred: {e}")
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
# 生成 SSH 密钥对
|
| 322 |
+
generate_ssh_key()
|
| 323 |
+
os.system('chmod 600 ~/.ssh/id_rsa')
|
| 324 |
+
# 复制公钥到远程服务器
|
| 325 |
+
copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
|
| 330 |
+
"""创建一个带重试机制的请求会话"""
|
| 331 |
+
session = session or requests.Session()
|
| 332 |
+
retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
|
| 333 |
+
adapter = HTTPAdapter(max_retries=retry)
|
| 334 |
+
session.mount('http://', adapter)
|
| 335 |
+
session.mount('https://', adapter)
|
| 336 |
+
return session
|
| 337 |
+
|
| 338 |
+
def write_rsyncd_conf(path, port=7075):
|
| 339 |
+
rsyncd_conf_content = f"""
|
| 340 |
+
port = {port}
|
| 341 |
+
|
| 342 |
+
[qilan]
|
| 343 |
+
path = {path}
|
| 344 |
+
comment = My rsync module
|
| 345 |
+
read only = no
|
| 346 |
+
list = yes
|
| 347 |
+
"""
|
| 348 |
+
with open('/etc/rsyncd.conf', 'w') as f:
|
| 349 |
+
f.write(rsyncd_conf_content.strip())
|
| 350 |
+
print(f"Successfully wrote to /etc/rsyncd.conf for module .")
|
| 351 |
+
# os.system("sudo rsync --daemon")
|
| 352 |
+
# os.system("sudo rsync --daemon")
|
| 353 |
+
# os.system("sudo rsync --daemon")
|
| 354 |
+
# os.system("sudo rsync --daemon")
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
import os
|
| 358 |
+
import time
|
| 359 |
+
import requests
|
| 360 |
+
import subprocess
|
| 361 |
+
import logging
|
| 362 |
+
|
| 363 |
+
# 配置日志
|
| 364 |
+
logging.basicConfig(level=logging.INFO)
|
| 365 |
+
|
| 366 |
+
def check_api1():
|
| 367 |
+
# 第一次检查 Card_Hub 是否启动
|
| 368 |
+
thread_started = False
|
| 369 |
+
n = 0
|
| 370 |
+
while True:
|
| 371 |
+
n += 1
|
| 372 |
+
if not os.path.exists('/Card_Hub'):
|
| 373 |
+
logging.error(f"/Card_Hub/ 文件不存在,结束检测")
|
| 374 |
+
break
|
| 375 |
+
try:
|
| 376 |
+
url = "http://127.0.0.1:8003/api/auth/login"
|
| 377 |
+
response = requests.get(url, timeout=30)
|
| 378 |
+
|
| 379 |
+
if response.status_code == 401:
|
| 380 |
+
print("Card_Hub已经启动")
|
| 381 |
+
break
|
| 382 |
+
|
| 383 |
+
print("Card_Hub未启动,状态码:", response.status_code, n)
|
| 384 |
+
|
| 385 |
+
except requests.exceptions.RequestException as e:
|
| 386 |
+
print(f"Card_Hub未启动3: {e}, 尝试次数: {n}")
|
| 387 |
+
|
| 388 |
+
time.sleep(5)
|
| 389 |
+
|
| 390 |
+
print('Card_Hub本地已经运行,开始检测接口状态')
|
| 391 |
+
Service_status = False
|
| 392 |
+
n = 0
|
| 393 |
+
nn = 0
|
| 394 |
+
while True:
|
| 395 |
+
n += 1
|
| 396 |
+
if not os.path.exists('/Card_Hub'):
|
| 397 |
+
print(f"/Card_Hub/ 文件不存在,结束检测")
|
| 398 |
+
break
|
| 399 |
+
if Service_status:
|
| 400 |
+
print("结束检测")
|
| 401 |
+
break
|
| 402 |
+
if nn > 2:
|
| 403 |
+
break
|
| 404 |
+
url = f"{st_url}/api/auth/login"
|
| 405 |
+
try:
|
| 406 |
+
response = requests_retry_session().get(url, timeout=30)
|
| 407 |
+
response.raise_for_status()
|
| 408 |
+
response_json = response.json()
|
| 409 |
+
print("%s 接口返回信息: %s", url, response_json) # 修正日志记录
|
| 410 |
+
if "token" in response_json:
|
| 411 |
+
print("检测到 token")
|
| 412 |
+
try:
|
| 413 |
+
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)
|
| 414 |
+
# break # 如果成功,跳出重试循环
|
| 415 |
+
except subprocess.CalledProcessError as e:
|
| 416 |
+
nn += 1
|
| 417 |
+
print(f"Rsync 失败,返回码: {e.returncode}, 尝试次数: {nn}")
|
| 418 |
+
generate_ssh_key() # 处理 SSH 密钥生成
|
| 419 |
+
else:
|
| 420 |
+
print("%s 接口返回信息: %s", url, response_json) # 修正日志记录
|
| 421 |
+
except requests.exceptions.ConnectionError as e:
|
| 422 |
+
print(f"接口异常1: {e}, 尝试次数: {n}, nn: {nn}")
|
| 423 |
+
# time.sleep(3)
|
| 424 |
+
nn += 1
|
| 425 |
+
if nn > 5:
|
| 426 |
+
break
|
| 427 |
+
except requests.exceptions.Timeout as e:
|
| 428 |
+
print(f"接口异常2: {e}, 尝试次数: {n}")
|
| 429 |
+
break
|
| 430 |
+
except requests.exceptions.RequestException as e:
|
| 431 |
+
print(f"接口异常3: {e}, 尝试次数: {n}")
|
| 432 |
+
break
|
| 433 |
+
|
| 434 |
+
time.sleep(5)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def frp(configs, backstage):
|
| 440 |
+
print('-----------FRP开始-------------')
|
| 441 |
+
# 遍历所有配置并启动 FRP。
|
| 442 |
+
for config_data, config_file_path in configs:
|
| 443 |
+
with open(config_file_path, 'w') as config_file:
|
| 444 |
+
config_file.write(config_data)
|
| 445 |
+
# 启动 frpc 命令和参数。
|
| 446 |
+
frpc_cmd=['/content/frp/frpc', '-c', config_file_path]
|
| 447 |
+
|
| 448 |
+
if backstage:
|
| 449 |
+
subprocess.Popen(frpc_cmd)
|
| 450 |
+
else:
|
| 451 |
+
subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True)
|
| 452 |
+
print('-----------FRP结束-------------')
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def monitor_port():
|
| 457 |
+
while True:
|
| 458 |
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
| 459 |
+
result = sock.connect_ex(('localhost', 8003))
|
| 460 |
+
if result == 0:
|
| 461 |
+
print(f"端口 8003 正在使用中")
|
| 462 |
+
else:
|
| 463 |
+
print(f"端口 8003 未被使用")
|
| 464 |
+
# 读取 config.ini 中的 monitor_port_enabled 配置项
|
| 465 |
+
config = configparser.ConfigParser()
|
| 466 |
+
config.read('/config.ini')
|
| 467 |
+
monitor_port_enabled = config.getboolean('general', 'monitor_port_enabled', fallback=False)
|
| 468 |
+
if monitor_port_enabled:
|
| 469 |
+
backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
|
| 470 |
+
backup_thread.start()
|
| 471 |
+
else:
|
| 472 |
+
print(f"monitor_port_enabled 为False跳过")
|
| 473 |
+
|
| 474 |
+
time.sleep(5) # 每5秒检查一次
|
| 475 |
+
def Run_SillyTavern():
|
| 476 |
+
os.chdir('/Card_Hub/RoleCardSite')
|
| 477 |
+
try:
|
| 478 |
+
# 启动 Node.js 服务器,并将输出重定向到 /dev/null
|
| 479 |
+
subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
| 480 |
+
subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
| 481 |
+
subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
| 482 |
+
subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
| 483 |
+
subprocess.run(f'yes | sh {data_folder}/start.sh', shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
|
| 484 |
+
print("已尝试启动 server.js")
|
| 485 |
+
except subprocess.CalledProcessError as e:
|
| 486 |
+
print(f"命令失败,返回码: {e.returncode}")
|
| 487 |
+
except Exception as e: # 捕获所有其他异常
|
| 488 |
+
print(f"发生异常: {e}")
|
| 489 |
+
|
| 490 |
+
def SillyTavern():
|
| 491 |
+
print('-----------SillyTavern开始-------------')
|
| 492 |
+
# 创建目录并写入 kaggle.json
|
| 493 |
+
os.system("mkdir -p ~/.kaggle")
|
| 494 |
+
file_path = '/root/.kaggle/kaggle.json'
|
| 495 |
+
with open(file_path, 'w') as json_file:
|
| 496 |
+
json.dump(ini_content, json_file, indent=4)
|
| 497 |
+
os.system("chmod 600 ~/.kaggle/kaggle.json")
|
| 498 |
+
|
| 499 |
+
clear_output()
|
| 500 |
+
|
| 501 |
+
os.system(f"rm -r /a /card-hub /*.zi* {data_folder}")
|
| 502 |
+
os.system(f"mkdir -p {data_folder}")
|
| 503 |
+
os.chdir('/')
|
| 504 |
+
print(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
|
| 505 |
+
# os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name}")
|
| 506 |
+
download_n = 0
|
| 507 |
+
while True:
|
| 508 |
+
# 执行下载命令
|
| 509 |
+
if download_n > 6:
|
| 510 |
+
break
|
| 511 |
+
os.system(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
|
| 512 |
+
# 检查文件是否存在
|
| 513 |
+
if os.path.exists(f'/{huggingface_Data_name}.zip'):
|
| 514 |
+
print(f"{huggingface_Data_name}.zip 下载成功!")
|
| 515 |
+
break # 跳出循环
|
| 516 |
+
print(f"{huggingface_Data_name}.zip 下载失败,正在重试...")
|
| 517 |
+
download_n += 1
|
| 518 |
+
time.sleep(300) # 等待一段时间再重试(例如5秒
|
| 519 |
+
# os.system('kaggle datasets download xovale7506/sillytavern-data2')
|
| 520 |
+
# 检查文件是否存在
|
| 521 |
+
if not os.path.exists(f'/{huggingface_Data_name}.zip'):
|
| 522 |
+
print(f"文件 /{huggingface_Data_name}.zip 不存在,启用实时同步。")
|
| 523 |
+
generate_ssh_key()
|
| 524 |
+
copy_public_key_to_remote(ssh_url, ssh_port, "root", "qilan")
|
| 525 |
+
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)
|
| 526 |
+
else:
|
| 527 |
+
|
| 528 |
+
# 如果文件存在,可以继续执行后续代码
|
| 529 |
+
print(f"文件 /{huggingface_Data_name}.zip 存在,继续执行程序。")
|
| 530 |
+
os.system(f"7z x /{huggingface_Data_name}.zip -o/ -y")
|
| 531 |
+
os.system("mv /Card_Hub.ctk card-hub.tar.gz")
|
| 532 |
+
os.system("mv /card_Hub.ctk card-hub.tar.gz")
|
| 533 |
+
os.system("ls /")
|
| 534 |
+
os.system(f"tar -xvpf /card-hub.tar.gz -C / --use-compress-program=pigz > /dev/null")
|
| 535 |
+
|
| 536 |
+
print('更新文件')
|
| 537 |
+
# os.system('git pull --rebase --autostash')
|
| 538 |
+
backup_thread = threading.Thread(target=Run_SillyTavern, daemon=True)
|
| 539 |
+
backup_thread.start()
|
| 540 |
+
os.system("rn -r /card-hub.zip /Card_Hub.ctk")
|
| 541 |
+
print('-----------SillyTavern结束-------------')
|
| 542 |
+
threading.Thread(target=SillyTavern, daemon=True).start()
|
| 543 |
+
time.sleep(60)
|
| 544 |
+
check_api1()
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
# 创建 ConfigParser 对象
|
| 548 |
+
config = configparser.ConfigParser()
|
| 549 |
+
# 添加一个 'general' 部分
|
| 550 |
+
config.add_section('general')
|
| 551 |
+
# 设置 'monitor_port_enabled' 选项的值为 True
|
| 552 |
+
config.set('general', 'monitor_port_enabled', 'True')
|
| 553 |
+
# 将配置写入到 'config.ini' 文件中
|
| 554 |
+
with open('/config.ini', 'w') as configfile:
|
| 555 |
+
config.write(configfile)
|
| 556 |
+
if os.path.exists(f'/Card_Hub/RoleCardSite/start.sh'):
|
| 557 |
+
backup_thread = threading.Thread(target=repeat_task, daemon=True)#压缩备份
|
| 558 |
+
backup_thread.start()
|
| 559 |
+
print("开始衔接")
|
| 560 |
+
Service_status = True
|
| 561 |
+
frp(configs, True)
|
| 562 |
+
threading.Thread(target=monitor_port, daemon=True).start()#检测端口状态
|
| 563 |
+
while True:
|
| 564 |
+
if backup_thread.is_alive():
|
| 565 |
+
print("备份线程仍在运行...")
|
| 566 |
+
else:
|
| 567 |
+
print("备份线程已停止.")
|
| 568 |
+
backup_thread = threading.Thread(target=repeat_task, daemon=True)
|
| 569 |
+
backup_thread.start()
|
| 570 |
+
# break
|
| 571 |
+
time.sleep(5)
|
| 572 |
+
|
| 573 |
+
else:
|
| 574 |
+
print("/sillytavern 文件不存在结束执行")
|
| 575 |
+
compress_folder()
|