Update server9-bf.py
Browse files- server9-bf.py +100 -186
server9-bf.py
CHANGED
|
@@ -50,11 +50,9 @@ kaggle_metadata = {
|
|
| 50 |
"licenses": [{"name": "CC0-1.0"}]
|
| 51 |
}
|
| 52 |
|
| 53 |
-
# 全局状态变量
|
| 54 |
last_uploaded_size = -1
|
| 55 |
lock = threading.Lock()
|
| 56 |
|
| 57 |
-
# FRP 配置文件列表
|
| 58 |
configs = [
|
| 59 |
("""
|
| 60 |
[common]
|
|
@@ -150,7 +148,6 @@ configs = [
|
|
| 150 |
# 2. 核心通用工具函数
|
| 151 |
# ==========================================
|
| 152 |
def run_cmd(command, ignore_errors=False, quiet=False):
|
| 153 |
-
"""统一的命令执行工具,替代 os.system"""
|
| 154 |
try:
|
| 155 |
stdout = subprocess.DEVNULL if quiet else None
|
| 156 |
stderr = subprocess.DEVNULL if quiet else None
|
|
@@ -160,7 +157,6 @@ def run_cmd(command, ignore_errors=False, quiet=False):
|
|
| 160 |
logging.error(f"命令执行失败: {command}\n错误码: {e.returncode}")
|
| 161 |
|
| 162 |
def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
|
| 163 |
-
"""带重试机制的请求会话"""
|
| 164 |
session = session or requests.Session()
|
| 165 |
retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
|
| 166 |
adapter = HTTPAdapter(max_retries=retry)
|
|
@@ -187,35 +183,27 @@ def init_environment():
|
|
| 187 |
run_cmd("rm -r /sync.sh", ignore_errors=True, quiet=True)
|
| 188 |
run_cmd("wget -q -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
|
| 189 |
run_cmd("export LC_ALL=zh_CN.UTF-8")
|
| 190 |
-
|
| 191 |
run_cmd("mkdir -p /content/frp")
|
| 192 |
run_cmd("wget -q https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
|
| 193 |
run_cmd("chmod +x /content/frp/frpc")
|
| 194 |
-
|
| 195 |
-
if not is_installed('
|
| 196 |
-
install_package('nodejs')
|
| 197 |
-
if not is_installed('npm'):
|
| 198 |
-
install_package('npm')
|
| 199 |
-
|
| 200 |
run_cmd("pip uninstall requests urllib3 -y", quiet=True)
|
| 201 |
run_cmd("pip install requests urllib3 ruamel.yaml pexpect pytz", quiet=True)
|
| 202 |
run_cmd("apt-get install -y sshpass p7zip-full pigz pv", quiet=True)
|
| 203 |
logging.info('-----------更新软件包列表结束-------------')
|
| 204 |
|
| 205 |
-
def
|
| 206 |
if install_ssh_config:
|
| 207 |
run_cmd("sudo mkdir -p --mode=0755 /usr/share/keyrings")
|
| 208 |
run_cmd("curl -fsSL https://pkg.cloudflare.com/cloudflare-public-v2.gpg | sudo tee /usr/share/keyrings/cloudflare-public-v2.gpg >/dev/null")
|
| 209 |
run_cmd("echo 'deb [signed-by=/usr/share/keyrings/cloudflare-public-v2.gpg] https://pkg.cloudflare.com/cloudflared any main' | sudo tee /etc/apt/sources.list.d/cloudflared.list")
|
| 210 |
run_cmd("sudo apt-get update && sudo apt-get install cloudflared -y", quiet=True)
|
| 211 |
-
|
| 212 |
ssh_dir = os.path.expanduser("~/.ssh")
|
| 213 |
os.makedirs(ssh_dir, exist_ok=True)
|
| 214 |
ssh_config_content = f"Host {cf_ssh}\n ProxyCommand cloudflared access ssh --hostname %h\n StrictHostKeyChecking no\n"
|
| 215 |
-
|
| 216 |
config_path = os.path.join(ssh_dir, "config")
|
| 217 |
-
with open(config_path, "w") as f:
|
| 218 |
-
f.write(ssh_config_content)
|
| 219 |
os.chmod(config_path, 0o600)
|
| 220 |
else:
|
| 221 |
run_cmd(f"sudo cloudflared service install {cf_token}", quiet=True)
|
|
@@ -225,7 +213,6 @@ def setup_ssh():
|
|
| 225 |
run_cmd("apt update && apt install openssh-server vim -y", quiet=True)
|
| 226 |
run_cmd("sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config")
|
| 227 |
run_cmd("sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config")
|
| 228 |
-
|
| 229 |
run_cmd("echo 'root:qilan' | sudo chpasswd")
|
| 230 |
run_cmd("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
|
| 231 |
run_cmd("service ssh restart", quiet=True)
|
|
@@ -250,218 +237,154 @@ def copy_public_key_to_remote(host, port, user, password):
|
|
| 250 |
# 4. 接力信息修改模块 (IP与接力时间)
|
| 251 |
# ==========================================
|
| 252 |
def get_current_ip():
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
response = requests.get("https://ipinfo.io/ip", timeout=5)
|
| 256 |
-
return response.text.strip()
|
| 257 |
-
except:
|
| 258 |
-
return "Unknown IP"
|
| 259 |
|
| 260 |
def get_geo_info(ip_address):
|
| 261 |
-
"""根据 IP 地址获取地理位置信息"""
|
| 262 |
-
url = "https://api.qjqq.cn/api/Local"
|
| 263 |
-
headers = {
|
| 264 |
-
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
|
| 265 |
-
}
|
| 266 |
try:
|
| 267 |
-
response = requests.get(
|
| 268 |
-
if response.status_code == 200:
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
return {'ip': data['ip'], 'country': data['country'], 'isp': data['isp']}
|
| 273 |
-
except Exception as e:
|
| 274 |
-
logging.error(f"获取地理位置失败: {e}")
|
| 275 |
return None
|
| 276 |
|
| 277 |
def get_next_relay_time():
|
| 278 |
-
"""获取下一次接力时间(系统启动时间+12小时,转换为中国时区)"""
|
| 279 |
try:
|
| 280 |
boot_time = datetime.fromtimestamp(psutil.boot_time())
|
| 281 |
-
utc = pytz.UTC
|
| 282 |
-
boot_time = utc.localize(boot_time)
|
| 283 |
china_tz = pytz.timezone('Asia/Shanghai')
|
| 284 |
-
|
| 285 |
-
next_time = boot_time_china + timedelta(hours=12)
|
| 286 |
return next_time.strftime("%Y-%m-%d %H:%M:%S")
|
| 287 |
-
except
|
| 288 |
-
logging.error(f"计算接力时间失败: {e}")
|
| 289 |
-
return "未知时间"
|
| 290 |
|
| 291 |
def replace_info_in_file(file_path):
|
| 292 |
-
"""修改 ST 登录界面的 IP 和接力时间信息"""
|
| 293 |
try:
|
| 294 |
-
if not os.path.exists(file_path):
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
with open(file_path, 'r', encoding='utf-8') as file:
|
| 304 |
-
content = file.read()
|
| 305 |
-
|
| 306 |
-
time_pattern = r'接力时间\[.*?\]'
|
| 307 |
-
time_replacement = f'接力时间[{next_relay_time}]'
|
| 308 |
-
content = re.sub(time_pattern, time_replacement, content)
|
| 309 |
-
|
| 310 |
-
ip_pattern = r'IP\[.*?\]\s*国家\s*\[.*?\]\s*IPS\[.*?\]'
|
| 311 |
-
ip_replacement = f'IP[{ip_address}] 国家 [{geo_info["country"]}] IPS[{geo_info["isp"]}]'
|
| 312 |
-
content = re.sub(ip_pattern, ip_replacement, content)
|
| 313 |
-
|
| 314 |
-
with open(file_path, 'w', encoding='utf-8') as file:
|
| 315 |
-
file.write(content)
|
| 316 |
-
|
| 317 |
-
logging.info(f"成功更新前端页面信息: 接力时间[{next_relay_time}], IP[{ip_address}]")
|
| 318 |
-
except Exception as e:
|
| 319 |
-
logging.error(f"替换前端信息时发生错误: {e}")
|
| 320 |
|
| 321 |
# ==========================================
|
| 322 |
# 5. 双机接力 rsync 数据同步核心
|
| 323 |
# ==========================================
|
| 324 |
def sync_data_via_rsync():
|
| 325 |
-
"""
|
| 326 |
-
logging.info("------ 开始执行双机接力同步检测
|
| 327 |
-
|
| 328 |
-
# 第一步:等待本地 ST 服务完全启动
|
| 329 |
retry_n = 0
|
| 330 |
while True:
|
| 331 |
-
|
| 332 |
-
if not os.path.exists(data_folder):
|
| 333 |
-
logging.error(f"{data_folder} 不存在,结束接力检测。")
|
| 334 |
-
return
|
| 335 |
try:
|
| 336 |
-
|
| 337 |
-
if response.status_code == 403:
|
| 338 |
logging.info("SillyTavern 本地接口已启动!")
|
| 339 |
break
|
| 340 |
-
except requests.exceptions.RequestException:
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
if retry_n % 12 == 0:
|
| 344 |
-
logging.info("等待本地 SillyTavern 启动中...")
|
| 345 |
time.sleep(5)
|
| 346 |
|
| 347 |
-
# 第二步:检测旧机器(远程)接口 token,触发 rsync 数据拉取
|
| 348 |
-
logging.info('ST本地已就绪,开始探测前置机器(旧机器)以触发同步...')
|
| 349 |
fail_count = 0
|
| 350 |
while fail_count <= 5:
|
| 351 |
-
if not os.path.exists(data_folder):
|
| 352 |
-
break
|
| 353 |
-
|
| 354 |
-
url = f"{cf_jg}/csrf-token"
|
| 355 |
try:
|
| 356 |
-
response = requests_retry_session().get(
|
| 357 |
-
response.
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 374 |
else:
|
| 375 |
-
logging.warning(f"接口未返回 token: {response_json}")
|
| 376 |
fail_count += 1
|
| 377 |
-
|
| 378 |
except Exception as e:
|
| 379 |
fail_count += 1
|
| 380 |
-
logging.
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
time.sleep(5)
|
| 385 |
-
logging.info("------ 双机接力环节执行完毕 ------")
|
| 386 |
|
| 387 |
# ==========================================
|
| 388 |
# 6. 后台备份、FRP 与进程守护
|
| 389 |
# ==========================================
|
| 390 |
-
def get_folder_size(folder):
|
| 391 |
-
try:
|
| 392 |
-
result = subprocess.run(['du', '-sb', folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 393 |
-
if result.returncode == 0:
|
| 394 |
-
return int(result.stdout.split()[0])
|
| 395 |
-
except:
|
| 396 |
-
return 0
|
| 397 |
-
|
| 398 |
def compress_folder():
|
| 399 |
global last_uploaded_size
|
| 400 |
run_cmd('rm -rf /a/', ignore_errors=True, quiet=True)
|
| 401 |
os.makedirs('/a', exist_ok=True)
|
| 402 |
-
|
| 403 |
with lock:
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
|
|
|
|
|
|
|
|
|
| 407 |
|
| 408 |
if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
|
| 409 |
logging.info('开始压缩打包数据用于备份...')
|
| 410 |
run_cmd(f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path}', quiet=True)
|
|
|
|
|
|
|
| 411 |
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
if not os.path.exists(file_path):
|
| 415 |
-
return
|
| 416 |
-
|
| 417 |
-
file_size = os.path.getsize(file_path)
|
| 418 |
-
if file_size < (800 * 1024 ** 2):
|
| 419 |
-
return
|
| 420 |
|
| 421 |
logging.info("准备将压缩包上传至 Kaggle...")
|
| 422 |
-
with open(metadata_file_path, 'w') as
|
| 423 |
-
json.dump(kaggle_metadata, json_fid)
|
| 424 |
-
|
| 425 |
run_cmd('kaggle datasets version -m "Auto Backup Update" -p /a')
|
| 426 |
last_uploaded_size = file_size
|
| 427 |
|
| 428 |
def repeat_task():
|
| 429 |
logging.info('------后台定时打包备份线程已启动-------------')
|
| 430 |
while True:
|
| 431 |
-
time.sleep(18000)
|
| 432 |
compress_folder()
|
| 433 |
|
| 434 |
def kill_frpc_processes():
|
| 435 |
-
try:
|
| 436 |
-
|
| 437 |
-
except subprocess.CalledProcessError:
|
| 438 |
-
pass
|
| 439 |
|
| 440 |
def frp(configs, backstage):
|
| 441 |
logging.info('-----------启动 FRP 内网穿透-------------')
|
| 442 |
for config_data, config_file_path in configs:
|
| 443 |
-
with open(config_file_path, 'w') as config_file:
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
if backstage:
|
| 448 |
-
subprocess.Popen(frpc_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 449 |
-
else:
|
| 450 |
-
run_cmd(f'/content/frp/frpc -c {config_file_path}', quiet=True)
|
| 451 |
|
| 452 |
def Run_SillyTavern():
|
| 453 |
-
"""启动 Node 服务"""
|
| 454 |
os.chdir(data_folder)
|
| 455 |
-
try:
|
| 456 |
-
|
| 457 |
-
except Exception as e:
|
| 458 |
-
logging.error(f"SillyTavern 启动失败: {e}")
|
| 459 |
|
| 460 |
def monitor_port():
|
| 461 |
while True:
|
| 462 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
| 463 |
-
|
| 464 |
-
if result != 0:
|
| 465 |
config = configparser.ConfigParser()
|
| 466 |
config.read('/config.ini')
|
| 467 |
if config.getboolean('general', 'monitor_port_enabled', fallback=False):
|
|
@@ -474,20 +397,15 @@ def monitor_port():
|
|
| 474 |
def setup_sillytavern():
|
| 475 |
logging.info('-----------SillyTavern 基础数据部署开始-------------')
|
| 476 |
os.makedirs(os.path.expanduser("~/.kaggle"), exist_ok=True)
|
| 477 |
-
with open('/root/.kaggle/kaggle.json', 'w') as json_file:
|
| 478 |
-
json.dump(ini_content, json_file, indent=4)
|
| 479 |
run_cmd("chmod 600 ~/.kaggle/kaggle.json")
|
| 480 |
-
|
| 481 |
run_cmd(f"rm -rf /a /sillytavern /*.zi* {data_folder}", ignore_errors=True, quiet=True)
|
| 482 |
os.makedirs(data_folder, exist_ok=True)
|
| 483 |
os.chdir('/')
|
| 484 |
|
| 485 |
-
|
| 486 |
-
while download_n <= 6:
|
| 487 |
run_cmd(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
|
| 488 |
-
if os.path.exists(f'/{huggingface_Data_name}.zip'):
|
| 489 |
-
break
|
| 490 |
-
download_n += 1
|
| 491 |
time.sleep(5)
|
| 492 |
|
| 493 |
if not os.path.exists(f'/{huggingface_Data_name}.zip'):
|
|
@@ -503,65 +421,61 @@ def setup_sillytavern():
|
|
| 503 |
run_cmd("rm -f ip.py", quiet=True)
|
| 504 |
run_cmd("wget -q -O /root/SillyTavern/ip.py https://huggingface.co/datasets/Qilan2/st-server/raw/main/ip.py")
|
| 505 |
run_cmd("python /root/SillyTavern/ip.py", ignore_errors=True, quiet=True)
|
| 506 |
-
|
| 507 |
os.chdir(data_folder)
|
| 508 |
run_cmd("nvm install node && nvm use node && npm install -y", quiet=True)
|
| 509 |
run_cmd(f'yes | sh {data_folder}/start.sh', quiet=True)
|
| 510 |
-
|
| 511 |
threading.Thread(target=Run_SillyTavern, daemon=True).start()
|
| 512 |
|
| 513 |
if __name__ == '__main__':
|
| 514 |
# 1. 基础环境预热
|
| 515 |
init_environment()
|
| 516 |
kill_frpc_processes()
|
| 517 |
-
|
| 518 |
setup_ssh()
|
| 519 |
-
|
| 520 |
generate_ssh_key()
|
| 521 |
copy_public_key_to_remote(cf_ssh, 22, "root", "qilan")
|
| 522 |
|
| 523 |
-
# 2.
|
| 524 |
threading.Thread(target=setup_sillytavern, daemon=True).start()
|
| 525 |
|
| 526 |
# 3. 智能等待基础数据就绪
|
| 527 |
-
logging.info("正在等待数据下载和解压,
|
| 528 |
wait_seconds = 0
|
| 529 |
while not os.path.exists(f'{data_folder}/start.sh'):
|
| 530 |
time.sleep(5)
|
| 531 |
-
wait_seconds
|
| 532 |
-
if wait_seconds > 1800:
|
| 533 |
logging.error("下载/解压超时(超过30分钟)!")
|
| 534 |
break
|
| 535 |
|
| 536 |
if os.path.exists(f'{data_folder}/start.sh'):
|
| 537 |
logging.info("SillyTavern 基础文件已就绪!")
|
| 538 |
|
| 539 |
-
# 4. 执行
|
| 540 |
sync_data_via_rsync()
|
|
|
|
|
|
|
|
|
|
| 541 |
|
| 542 |
-
#
|
| 543 |
replace_info_in_file(f'{data_folder}/public/login.html')
|
| 544 |
|
| 545 |
-
#
|
| 546 |
config = configparser.ConfigParser()
|
| 547 |
config.add_section('general')
|
| 548 |
config.set('general', 'monitor_port_enabled', 'True')
|
| 549 |
-
with open('/config.ini', 'w') as configfile:
|
| 550 |
-
config.write(configfile)
|
| 551 |
-
|
| 552 |
run_cmd("rm -rf /qilan-st9.zip /sillytavern.tar.gz", ignore_errors=True, quiet=True)
|
| 553 |
|
| 554 |
-
#
|
| 555 |
if os.path.exists(f'{data_folder}/start.sh'):
|
| 556 |
backup_thread = threading.Thread(target=repeat_task, daemon=True)
|
| 557 |
backup_thread.start()
|
| 558 |
|
| 559 |
logging.info("前置任务全部完结!启动端口监控和网络穿透通道...")
|
| 560 |
frp(configs, True)
|
| 561 |
-
|
| 562 |
threading.Thread(target=monitor_port, daemon=True).start()
|
| 563 |
|
| 564 |
-
# 存活守护循环
|
| 565 |
while True:
|
| 566 |
if not backup_thread.is_alive():
|
| 567 |
backup_thread = threading.Thread(target=repeat_task, daemon=True)
|
|
|
|
| 50 |
"licenses": [{"name": "CC0-1.0"}]
|
| 51 |
}
|
| 52 |
|
|
|
|
| 53 |
last_uploaded_size = -1
|
| 54 |
lock = threading.Lock()
|
| 55 |
|
|
|
|
| 56 |
configs = [
|
| 57 |
("""
|
| 58 |
[common]
|
|
|
|
| 148 |
# 2. 核心通用工具函数
|
| 149 |
# ==========================================
|
| 150 |
def run_cmd(command, ignore_errors=False, quiet=False):
|
|
|
|
| 151 |
try:
|
| 152 |
stdout = subprocess.DEVNULL if quiet else None
|
| 153 |
stderr = subprocess.DEVNULL if quiet else None
|
|
|
|
| 157 |
logging.error(f"命令执行失败: {command}\n错误码: {e.returncode}")
|
| 158 |
|
| 159 |
def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):
|
|
|
|
| 160 |
session = session or requests.Session()
|
| 161 |
retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)
|
| 162 |
adapter = HTTPAdapter(max_retries=retry)
|
|
|
|
| 183 |
run_cmd("rm -r /sync.sh", ignore_errors=True, quiet=True)
|
| 184 |
run_cmd("wget -q -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh")
|
| 185 |
run_cmd("export LC_ALL=zh_CN.UTF-8")
|
|
|
|
| 186 |
run_cmd("mkdir -p /content/frp")
|
| 187 |
run_cmd("wget -q https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc")
|
| 188 |
run_cmd("chmod +x /content/frp/frpc")
|
| 189 |
+
if not is_installed('nodejs'): install_package('nodejs')
|
| 190 |
+
if not is_installed('npm'): install_package('npm')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
run_cmd("pip uninstall requests urllib3 -y", quiet=True)
|
| 192 |
run_cmd("pip install requests urllib3 ruamel.yaml pexpect pytz", quiet=True)
|
| 193 |
run_cmd("apt-get install -y sshpass p7zip-full pigz pv", quiet=True)
|
| 194 |
logging.info('-----------更新软件包列表结束-------------')
|
| 195 |
|
| 196 |
+
def setup_cloudflared(install_ssh_config=True):
|
| 197 |
if install_ssh_config:
|
| 198 |
run_cmd("sudo mkdir -p --mode=0755 /usr/share/keyrings")
|
| 199 |
run_cmd("curl -fsSL https://pkg.cloudflare.com/cloudflare-public-v2.gpg | sudo tee /usr/share/keyrings/cloudflare-public-v2.gpg >/dev/null")
|
| 200 |
run_cmd("echo 'deb [signed-by=/usr/share/keyrings/cloudflare-public-v2.gpg] https://pkg.cloudflare.com/cloudflared any main' | sudo tee /etc/apt/sources.list.d/cloudflared.list")
|
| 201 |
run_cmd("sudo apt-get update && sudo apt-get install cloudflared -y", quiet=True)
|
|
|
|
| 202 |
ssh_dir = os.path.expanduser("~/.ssh")
|
| 203 |
os.makedirs(ssh_dir, exist_ok=True)
|
| 204 |
ssh_config_content = f"Host {cf_ssh}\n ProxyCommand cloudflared access ssh --hostname %h\n StrictHostKeyChecking no\n"
|
|
|
|
| 205 |
config_path = os.path.join(ssh_dir, "config")
|
| 206 |
+
with open(config_path, "w") as f: f.write(ssh_config_content)
|
|
|
|
| 207 |
os.chmod(config_path, 0o600)
|
| 208 |
else:
|
| 209 |
run_cmd(f"sudo cloudflared service install {cf_token}", quiet=True)
|
|
|
|
| 213 |
run_cmd("apt update && apt install openssh-server vim -y", quiet=True)
|
| 214 |
run_cmd("sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config")
|
| 215 |
run_cmd("sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config")
|
|
|
|
| 216 |
run_cmd("echo 'root:qilan' | sudo chpasswd")
|
| 217 |
run_cmd("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config")
|
| 218 |
run_cmd("service ssh restart", quiet=True)
|
|
|
|
| 237 |
# 4. 接力信息修改模块 (IP与接力时间)
|
| 238 |
# ==========================================
|
| 239 |
def get_current_ip():
|
| 240 |
+
try: return requests.get("https://ipinfo.io/ip", timeout=5).text.strip()
|
| 241 |
+
except: return "Unknown IP"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
def get_geo_info(ip_address):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
try:
|
| 245 |
+
response = requests.get("https://api.qjqq.cn/api/Local", headers={"User-Agent": "Mozilla/5.0"}, timeout=5)
|
| 246 |
+
if response.status_code == 200 and response.json().get('code') == 200:
|
| 247 |
+
data = response.json()['data']
|
| 248 |
+
return {'ip': data['ip'], 'country': data['country'], 'isp': data['isp']}
|
| 249 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
| 250 |
return None
|
| 251 |
|
| 252 |
def get_next_relay_time():
|
|
|
|
| 253 |
try:
|
| 254 |
boot_time = datetime.fromtimestamp(psutil.boot_time())
|
|
|
|
|
|
|
| 255 |
china_tz = pytz.timezone('Asia/Shanghai')
|
| 256 |
+
next_time = pytz.UTC.localize(boot_time).astimezone(china_tz) + timedelta(hours=12)
|
|
|
|
| 257 |
return next_time.strftime("%Y-%m-%d %H:%M:%S")
|
| 258 |
+
except: return "未知时间"
|
|
|
|
|
|
|
| 259 |
|
| 260 |
def replace_info_in_file(file_path):
|
|
|
|
| 261 |
try:
|
| 262 |
+
if not os.path.exists(file_path): return
|
| 263 |
+
ip_address, geo_info, next_relay_time = get_current_ip(), get_geo_info(get_current_ip()), get_next_relay_time()
|
| 264 |
+
if geo_info:
|
| 265 |
+
with open(file_path, 'r', encoding='utf-8') as f: content = f.read()
|
| 266 |
+
content = re.sub(r'接力时间\[.*?\]', f'接力时间[{next_relay_time}]', content)
|
| 267 |
+
content = re.sub(r'IP\[.*?\]\s*国家\s*\[.*?\]\s*IPS\[.*?\]', f'IP[{ip_address}] 国家 [{geo_info["country"]}] IPS[{geo_info["isp"]}]', content)
|
| 268 |
+
with open(file_path, 'w', encoding='utf-8') as f: f.write(content)
|
| 269 |
+
logging.info(f"前端页面更新成功: 接力时间[{next_relay_time}], IP[{ip_address}]")
|
| 270 |
+
except Exception as e: logging.error(f"替换前端信息发生错误: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
|
| 272 |
# ==========================================
|
| 273 |
# 5. 双机接力 rsync 数据同步核心
|
| 274 |
# ==========================================
|
| 275 |
def sync_data_via_rsync():
|
| 276 |
+
"""首次初始化阻断式同步"""
|
| 277 |
+
logging.info("------ 开始执行首次双机接力同步检测 ------")
|
|
|
|
|
|
|
| 278 |
retry_n = 0
|
| 279 |
while True:
|
| 280 |
+
if not os.path.exists(data_folder): return
|
|
|
|
|
|
|
|
|
|
| 281 |
try:
|
| 282 |
+
if requests.get("http://127.0.0.1:8000/v1", timeout=10).status_code == 403:
|
|
|
|
| 283 |
logging.info("SillyTavern 本地接口已启动!")
|
| 284 |
break
|
| 285 |
+
except requests.exceptions.RequestException: pass
|
| 286 |
+
if (retry_n := retry_n + 1) % 12 == 0: logging.info("等待本地 ST 启动中...")
|
|
|
|
|
|
|
|
|
|
| 287 |
time.sleep(5)
|
| 288 |
|
|
|
|
|
|
|
| 289 |
fail_count = 0
|
| 290 |
while fail_count <= 5:
|
| 291 |
+
if not os.path.exists(data_folder): break
|
|
|
|
|
|
|
|
|
|
| 292 |
try:
|
| 293 |
+
response = requests_retry_session().get(f"{cf_jg}/csrf-token", timeout=15)
|
| 294 |
+
if response.status_code == 200 and "token" in response.json():
|
| 295 |
+
logging.info("成功探测到旧机器,执行首次全面接力拉取...")
|
| 296 |
+
# 注意这里加了 -u 参数,保护本地可能存在的新数据不被覆盖
|
| 297 |
+
subprocess.run(
|
| 298 |
+
f"sshpass -p 'qilan' rsync -avzu --timeout=600 -e 'ssh -p 22 -o StrictHostKeyChecking=no' root@{cf_ssh}:{data_folder}/ {data_folder}/",
|
| 299 |
+
shell=True, check=True
|
| 300 |
+
)
|
| 301 |
+
logging.info("首次拉取成功,旧机器数据已接管。")
|
| 302 |
+
break
|
| 303 |
+
else: fail_count += 1
|
| 304 |
+
except Exception as e:
|
| 305 |
+
fail_count += 1
|
| 306 |
+
if fail_count > 5: logging.warning("未检测到前置机器,可能已宕机,将使用本地数据。")
|
| 307 |
+
time.sleep(5)
|
| 308 |
+
|
| 309 |
+
def continuous_sync_task():
|
| 310 |
+
"""后台常驻:重叠期间每5分钟持续增量拉取旧机器数据"""
|
| 311 |
+
logging.info("------ 后台持续增量同步守护线程已启动 ------")
|
| 312 |
+
fail_count = 0
|
| 313 |
+
while fail_count < 5:
|
| 314 |
+
time.sleep(300) # 每5分钟探测拉取一次
|
| 315 |
+
try:
|
| 316 |
+
response = requests_retry_session().get(f"{cf_jg}/csrf-token", timeout=15)
|
| 317 |
+
if response.status_code == 200 and "token" in response.json():
|
| 318 |
+
logging.info("【接力中】探测到旧机器仍在运行,执行后台增量同步...")
|
| 319 |
+
# 核心:使用 -u (--update) 保证新机器上你产生的新聊天记录不会被旧机器覆盖!
|
| 320 |
+
subprocess.run(
|
| 321 |
+
f"sshpass -p 'qilan' rsync -avzu --timeout=600 -e 'ssh -p 22 -o StrictHostKeyChecking=no' root@{cf_ssh}:{data_folder}/ {data_folder}/",
|
| 322 |
+
shell=True, check=True, stdout=subprocess.DEVNULL
|
| 323 |
+
)
|
| 324 |
+
fail_count = 0 # 只要成功一次,就重置失败计数
|
| 325 |
else:
|
|
|
|
| 326 |
fail_count += 1
|
|
|
|
| 327 |
except Exception as e:
|
| 328 |
fail_count += 1
|
| 329 |
+
logging.info(f"探测旧机器异常,可能已关机。失败次数: {fail_count}/5")
|
| 330 |
+
|
| 331 |
+
logging.info("------ 旧机器已彻底离线,后台接力同步任务圆满结束 ------")
|
|
|
|
|
|
|
|
|
|
| 332 |
|
| 333 |
# ==========================================
|
| 334 |
# 6. 后台备份、FRP 与进程守护
|
| 335 |
# ==========================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
def compress_folder():
|
| 337 |
global last_uploaded_size
|
| 338 |
run_cmd('rm -rf /a/', ignore_errors=True, quiet=True)
|
| 339 |
os.makedirs('/a', exist_ok=True)
|
|
|
|
| 340 |
with lock:
|
| 341 |
+
try:
|
| 342 |
+
size_out = subprocess.run(['du', '-sb', data_folder], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
|
| 343 |
+
current_folder_size = int(size_out.stdout.split()[0]) if size_out.returncode == 0 else 0
|
| 344 |
+
except: return
|
| 345 |
+
|
| 346 |
+
if current_folder_size < (800 * 1024 ** 2): return
|
| 347 |
|
| 348 |
if last_uploaded_size == -1 or current_folder_size != last_uploaded_size:
|
| 349 |
logging.info('开始压缩打包数据用于备份...')
|
| 350 |
run_cmd(f'tar -cvf - {data_folder} | pigz -p 2 -1 > {zip_file_path}', quiet=True)
|
| 351 |
+
run_cmd(f'mv {zip_file_path} /a/sillytavern.ctk', ignore_errors=True)
|
| 352 |
+
if not os.path.exists("/a/sillytavern.ctk"): return
|
| 353 |
|
| 354 |
+
file_size = os.path.getsize("/a/sillytavern.ctk")
|
| 355 |
+
if file_size < (800 * 1024 ** 2): return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
|
| 357 |
logging.info("准备将压缩包上传至 Kaggle...")
|
| 358 |
+
with open(metadata_file_path, 'w') as f: json.dump(kaggle_metadata, f)
|
|
|
|
|
|
|
| 359 |
run_cmd('kaggle datasets version -m "Auto Backup Update" -p /a')
|
| 360 |
last_uploaded_size = file_size
|
| 361 |
|
| 362 |
def repeat_task():
|
| 363 |
logging.info('------后台定时打包备份线程已启动-------------')
|
| 364 |
while True:
|
| 365 |
+
time.sleep(18000)
|
| 366 |
compress_folder()
|
| 367 |
|
| 368 |
def kill_frpc_processes():
|
| 369 |
+
try: subprocess.run(['pkill', '-f', 'frpc'], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 370 |
+
except subprocess.CalledProcessError: pass
|
|
|
|
|
|
|
| 371 |
|
| 372 |
def frp(configs, backstage):
|
| 373 |
logging.info('-----------启动 FRP 内网穿透-------------')
|
| 374 |
for config_data, config_file_path in configs:
|
| 375 |
+
with open(config_file_path, 'w') as config_file: config_file.write(config_data)
|
| 376 |
+
if backstage: subprocess.Popen(['/content/frp/frpc', '-c', config_file_path], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
| 377 |
+
else: run_cmd(f'/content/frp/frpc -c {config_file_path}', quiet=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
|
| 379 |
def Run_SillyTavern():
|
|
|
|
| 380 |
os.chdir(data_folder)
|
| 381 |
+
try: run_cmd(f'yes | sh {data_folder}/start.sh', quiet=True)
|
| 382 |
+
except Exception as e: logging.error(f"SillyTavern 启动失败: {e}")
|
|
|
|
|
|
|
| 383 |
|
| 384 |
def monitor_port():
|
| 385 |
while True:
|
| 386 |
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
| 387 |
+
if sock.connect_ex(('localhost', 8000)) != 0:
|
|
|
|
| 388 |
config = configparser.ConfigParser()
|
| 389 |
config.read('/config.ini')
|
| 390 |
if config.getboolean('general', 'monitor_port_enabled', fallback=False):
|
|
|
|
| 397 |
def setup_sillytavern():
|
| 398 |
logging.info('-----------SillyTavern 基础数据部署开始-------------')
|
| 399 |
os.makedirs(os.path.expanduser("~/.kaggle"), exist_ok=True)
|
| 400 |
+
with open('/root/.kaggle/kaggle.json', 'w') as json_file: json.dump(ini_content, json_file, indent=4)
|
|
|
|
| 401 |
run_cmd("chmod 600 ~/.kaggle/kaggle.json")
|
|
|
|
| 402 |
run_cmd(f"rm -rf /a /sillytavern /*.zi* {data_folder}", ignore_errors=True, quiet=True)
|
| 403 |
os.makedirs(data_folder, exist_ok=True)
|
| 404 |
os.chdir('/')
|
| 405 |
|
| 406 |
+
for _ in range(7):
|
|
|
|
| 407 |
run_cmd(f"kaggle datasets download {huggingface_name}/{huggingface_Data_name} -p /")
|
| 408 |
+
if os.path.exists(f'/{huggingface_Data_name}.zip'): break
|
|
|
|
|
|
|
| 409 |
time.sleep(5)
|
| 410 |
|
| 411 |
if not os.path.exists(f'/{huggingface_Data_name}.zip'):
|
|
|
|
| 421 |
run_cmd("rm -f ip.py", quiet=True)
|
| 422 |
run_cmd("wget -q -O /root/SillyTavern/ip.py https://huggingface.co/datasets/Qilan2/st-server/raw/main/ip.py")
|
| 423 |
run_cmd("python /root/SillyTavern/ip.py", ignore_errors=True, quiet=True)
|
|
|
|
| 424 |
os.chdir(data_folder)
|
| 425 |
run_cmd("nvm install node && nvm use node && npm install -y", quiet=True)
|
| 426 |
run_cmd(f'yes | sh {data_folder}/start.sh', quiet=True)
|
|
|
|
| 427 |
threading.Thread(target=Run_SillyTavern, daemon=True).start()
|
| 428 |
|
| 429 |
if __name__ == '__main__':
|
| 430 |
# 1. 基础环境预热
|
| 431 |
init_environment()
|
| 432 |
kill_frpc_processes()
|
| 433 |
+
setup_cloudflared(True)
|
| 434 |
setup_ssh()
|
|
|
|
| 435 |
generate_ssh_key()
|
| 436 |
copy_public_key_to_remote(cf_ssh, 22, "root", "qilan")
|
| 437 |
|
| 438 |
+
# 2. 启动 ST 解压与下载
|
| 439 |
threading.Thread(target=setup_sillytavern, daemon=True).start()
|
| 440 |
|
| 441 |
# 3. 智能等待基础数据就绪
|
| 442 |
+
logging.info("正在等待数据下载和解压,请耐心等待...")
|
| 443 |
wait_seconds = 0
|
| 444 |
while not os.path.exists(f'{data_folder}/start.sh'):
|
| 445 |
time.sleep(5)
|
| 446 |
+
if (wait_seconds := wait_seconds + 5) > 1800:
|
|
|
|
| 447 |
logging.error("下载/解压超时(超过30分钟)!")
|
| 448 |
break
|
| 449 |
|
| 450 |
if os.path.exists(f'{data_folder}/start.sh'):
|
| 451 |
logging.info("SillyTavern 基础文件已就绪!")
|
| 452 |
|
| 453 |
+
# 4. 执行首次强制阻断同步
|
| 454 |
sync_data_via_rsync()
|
| 455 |
+
|
| 456 |
+
# 5. 开启后台持续增量同步线程!(每5分钟一次,防覆盖保护,直到旧机器关机)
|
| 457 |
+
threading.Thread(target=continuous_sync_task, daemon=True).start()
|
| 458 |
|
| 459 |
+
# 6. 替换登录页面显示接力时间与当前机器IP
|
| 460 |
replace_info_in_file(f'{data_folder}/public/login.html')
|
| 461 |
|
| 462 |
+
# 7. 配置监控环境收尾
|
| 463 |
config = configparser.ConfigParser()
|
| 464 |
config.add_section('general')
|
| 465 |
config.set('general', 'monitor_port_enabled', 'True')
|
| 466 |
+
with open('/config.ini', 'w') as configfile: config.write(configfile)
|
|
|
|
|
|
|
| 467 |
run_cmd("rm -rf /qilan-st9.zip /sillytavern.tar.gz", ignore_errors=True, quiet=True)
|
| 468 |
|
| 469 |
+
# 8. 启动常驻守护服务
|
| 470 |
if os.path.exists(f'{data_folder}/start.sh'):
|
| 471 |
backup_thread = threading.Thread(target=repeat_task, daemon=True)
|
| 472 |
backup_thread.start()
|
| 473 |
|
| 474 |
logging.info("前置任务全部完结!启动端口监控和网络穿透通道...")
|
| 475 |
frp(configs, True)
|
| 476 |
+
setup_cloudflared(False)
|
| 477 |
threading.Thread(target=monitor_port, daemon=True).start()
|
| 478 |
|
|
|
|
| 479 |
while True:
|
| 480 |
if not backup_thread.is_alive():
|
| 481 |
backup_thread = threading.Thread(target=repeat_task, daemon=True)
|