| ini_content = {"username":"xovale7506","key":"502e30bafc004c02aa668a279df23f3e"} |
| frp_url = '8.219.240.86' |
| ssh_port = '7074' |
| st_url = f'http://{frp_url}:7073' |
| config_data = f""" |
| [common] |
| server_addr = {frp_url} |
| server_port = 7000 |
| |
| [safgha22] |
| type = tcp |
| local_ip = 127.0.0.1 |
| local_port = 8000 |
| remote_port = 7073 |
| [safabf22] |
| type = tcp |
| local_ip = 127.0.0.1 |
| local_port = 22 |
| remote_port = {ssh_port} |
| [saffg22] |
| type = tcp |
| local_ip = 127.0.0.1 |
| local_port = 3000 |
| remote_port = 7075 |
| """ |
| config_data2 = """ |
| [common] |
| server_addr = 120.26.228.135 |
| server_port = 7000 |
| |
| [safghac22] |
| type = tcp |
| local_ip = 127.0.0.1 |
| local_port = 8000 |
| remote_port = 7073 |
| """ |
|
|
| kaggle_metadata = { |
| "title": "Your Dataset Title", |
| "id": "xovale7506/sillytavern-data", |
| "licenses": [{"name": "CC0-1.0"}] |
| } |
| st_status = True |
| import subprocess |
| import os |
| import sys |
| from IPython.display import clear_output |
| import urllib.request |
| from pathlib import Path |
| import requests |
| import json |
| import threading |
| import time |
| import pexpect |
| import glob |
| from requests.adapters import HTTPAdapter |
| from requests.packages.urllib3.util.retry import Retry |
|
|
| os.system("rm -r /sync.sh") |
| os.system("wget -O /sync.sh https://huggingface.co/datasets/Qilan2/st-server/resolve/main/sync.sh") |
|
|
| os.system("export LC_ALL=zh_CN.UTF-8") |
| |
| def update(): |
| print('-----------更新软件包列表开始-------------') |
| os.system("sudo apt update") |
| |
| os.system("sudo apt install nodejs npm -y") |
| |
| os.system("sudo npm install -g forever") |
| |
| os.system("sudo apt install p7zip-full -y") |
| os.system("pip install -U kaggle") |
| os.system("apt-get install inotify-tools") |
| os.system("pip install ruamel.yaml") |
| os.system("pip install pexpect") |
| print('-----------更新软件包列表结束-------------') |
| update() |
| from ruamel.yaml import YAML |
| clear_output(wait=True) |
|
|
| def kill_frpc_processes(): |
| try: |
| |
| subprocess.run(['pkill', '-f', 'frpc'], check=True) |
| print("所有frpc进程已被结束。") |
| except subprocess.CalledProcessError as e: |
| |
| print(f"结束frpc进程时出错: {e}") |
| kill_frpc_processes() |
|
|
|
|
| |
| def Oneapi(): |
| print('-----------Oneapi中转开始-------------') |
| |
| os.system("rm -rf /one/one-api") |
| os.system("mkdir -p /one") |
| |
| url = "https://github.com/songquanpeng/one-api/releases/download/v0.6.8/one-api" |
| os.system(f"wget {url} -O /one/one-api") |
| |
| os.system("chmod +x /one/one-api") |
| |
| os.environ["THEME"] = "berry" |
| os.environ["TIKTOKEN_CACHE_DIR"] = os.getcwd() |
| |
| db_user = "oneapi" |
| db_password = "epBjK5ZKysCe6yr3" |
| db_host = "106.52.51.116" |
| db_port = "3306" |
| db_name = "oneapi" |
| dsn = f"{db_user}:{db_password}@tcp({db_host}:{db_port})/{db_name}" |
| os.environ["SQL_DSN"] = dsn |
| command = ['/one/one-api', '--port', '3000'] |
| process = subprocess.Popen(command) |
| print(f"OneAPI程序已在后台启动,进程ID为:{process.pid}") |
| print('-----------Oneapi中转结束-------------') |
| |
|
|
| |
| def run_command(command): |
| try: |
| subprocess.run(command, check=True, shell=True) |
| except subprocess.CalledProcessError as e: |
| print(f"An error occurred: {e}") |
| def ssh(): |
| print('-----------SSH开始-------------') |
| subprocess.run("apt update", check=True, shell=True) |
| subprocess.run("apt install openssh-server -y", check=True, shell=True) |
| subprocess.run("apt-get install vim -y", check=True, shell=True) |
| |
| config_client_cmd = "sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config" |
| subprocess.run(config_client_cmd, check=True, shell=True) |
| config_server_cmd = "sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config" |
| subprocess.run(config_server_cmd, check=True, shell=True) |
| run_command("systemctl restart ssh") |
|
|
| os.system("/etc/init.d/ssh restart") |
| os.system("echo 'root:qilan' | sudo chpasswd") |
| os.system("echo 'PermitRootLogin yes' | sudo tee -a /etc/ssh/sshd_config") |
| os.system("service ssh restart ") |
| os.system("export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\n' | grep -v '/opt/conda/lib' | paste -sd ':') ") |
| print('-----------SSH结束-------------') |
| ssh() |
| clear_output() |
|
|
| import json |
| import os |
| import subprocess |
| import threading |
| import time |
|
|
| |
| lock = threading.Lock() |
| data_folder = '/sillytavern/*' |
| zip_file_path = '/a/sillytavern.zip' |
| metadata_file_path = '/a/dataset-metadata.json' |
| last_uploaded_size = -1 |
|
|
| def update_last_uploaded_size(size): |
| global last_uploaded_size |
| last_uploaded_size = size |
|
|
|
|
|
|
| def compress_folder(): |
| global last_uploaded_size |
|
|
| |
| if os.path.exists('/a'): |
| subprocess.run(['rm', '-r', '/a']) |
|
|
| os.makedirs('/a', exist_ok=True) |
|
|
| with lock: |
| if os.path.exists(zip_file_path): |
| print(f"压缩文件 {zip_file_path} 已存在,跳过本次压缩。") |
| return |
| |
| print('开始压缩数据') |
| result = subprocess.run(['7z', 'a', '-tzip', '-mx=1','-mmt=2', zip_file_path, data_folder]) |
| |
| print('重命名压缩后的文件') |
| file_path = '/a/sillytavern.zip1' |
| subprocess.run(['mv', zip_file_path,file_path]) |
| if result.returncode != 0: |
| print("压缩失败,请检查7z命令是否正确") |
| return |
| |
| print(f"Data compressed into {file_path}") |
| |
| file_size = os.path.getsize(file_path) |
| print('文件大小:', file_size, '上次文件大小:', last_uploaded_size,file_size * 1024 ** 2) |
| |
| |
| if file_size < (800 * 1024 ** 2): |
| print("文件小于800MB,不进行上传。") |
| return |
| |
| if last_uploaded_size == -1 or file_size > last_uploaded_size: |
| |
| if last_uploaded_size == -1: |
| print("首次运行,正在执行上传...") |
| update_last_uploaded_size(file_size) |
|
|
| with open(metadata_file_path, 'w') as json_fid: |
| json.dump(kaggle_metadata, json_fid) |
|
|
| subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a']) |
| |
| last_uploaded_size = file_size |
| |
| elif file_size > last_uploaded_size: |
| print(f"新文件 {zip_file_path} 大于上次上传的大小,正在执行上传...") |
| update_last_uploaded_size(file_size) |
|
|
| with open(metadata_file_path, 'w') as json_fid: |
| json.dump(kaggle_metadata, json_fid) |
|
|
| subprocess.run(['kaggle', 'datasets', 'version', '-m', 'new version message', '-p', '/a']) |
| last_uploaded_size = file_size |
| |
| else: |
| print(f"新文件 {zip_file_path} 不大于上次上传的大小,跳过") |
|
|
|
|
| def repeat_task(): |
| print('------打包线程启动-------------') |
| while True: |
| print('等待打包') |
| time.sleep(600) |
| compress_folder() |
| print('------打包线程结束-------------') |
| |
| |
|
|
| import os |
| import subprocess |
| import pexpect |
|
|
| def generate_ssh_key(): |
| |
| os.system("rm -f ~/.ssh/id_rsa ~/.ssh/id_rsa.pub") |
| keygen_command = "ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''" |
| try: |
| result = subprocess.run(keygen_command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| print("SSH key pair generated.") |
| print(result.stdout.decode()) |
| except subprocess.CalledProcessError as e: |
| print(f"Failed to generate SSH key: {e.stderr.decode() if e.stderr else e}") |
|
|
| def copy_public_key_to_remote(host, port, user, password): |
| |
| try: |
| command = f"ssh-copy-id -o StrictHostKeyChecking=no -p {port} {user}@{host}" |
| child = pexpect.spawn(command) |
|
|
| |
| child.expect("password:", timeout=10) |
| child.sendline(password) |
|
|
| |
| child.expect(pexpect.EOF) |
| |
| print(child.before.decode()) |
| |
| except Exception as e: |
| print(f"An error occurred: {e}") |
|
|
|
|
| |
| generate_ssh_key() |
|
|
| |
| copy_public_key_to_remote(frp_url, ssh_port, "root", "qilan") |
| |
|
|
|
|
| def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None): |
| """创建一个带重试机制的请求会话""" |
| session = session or requests.Session() |
| retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist) |
| adapter = HTTPAdapter(max_retries=retry) |
| session.mount('http://', adapter) |
| session.mount('https://', adapter) |
| return session |
|
|
| def check_api1(): |
| |
| thread_started = False |
| n=0 |
| while True: |
| n = n + 1 |
| if st_status == False and n > 50: |
| print("/sillytavern 文件不存在,结束检测") |
| break |
| try: |
| url = "http://127.0.0.1:8000/v1" |
| response = requests.get(url, timeout=30) |
|
|
| |
| if response.status_code == 403: |
| print("SillyTavern已经启动") |
| break |
| |
| |
| print("SillyTavern未启动,状态码:", response.status_code) |
|
|
| except requests.exceptions.RequestException as e: |
| print(f"SillyTavern未启动3: {e}") |
| |
| time.sleep(5) |
| |
| print('开始检测接口状态') |
| Service_status = False |
| |
| n = 0 |
| while True: |
| n = n + 1 |
| if st_status == False and n > 50: |
| print("/sillytavern 文件不存在,结束检测") |
| break |
| if Service_status: |
| print("结束检测") |
| break |
| url = f"{st_url}/csrf-token" |
| try: |
| response = requests_retry_session().get(url, timeout=30) |
| response.raise_for_status() |
| |
| response_json = response.json() |
| print(url,"接口返回信息:", response_json) |
| if "token" in response_json: |
| print("检测到 token") |
| |
| |
| |
| |
| |
| |
| subprocess.run(f"sh /sync.sh -p {ssh_port} -s {frp_url}", shell=True, check=True) |
| break |
| else: |
| print("接口返回信息:", response_json) |
| |
| except requests.exceptions.ConnectionError as e: |
| print(f"接口异常1: {e}") |
| |
| break |
| |
| except requests.exceptions.Timeout as e: |
| print(f"接口异常2: {e}") |
| |
| break |
| |
| except requests.exceptions.RequestException as e: |
| print(f"接口异常3: {e}") |
| |
| break |
| |
| time.sleep(5) |
|
|
|
|
| def frp(config_data1,config_file_path,backstage): |
| print('-----------FRP开始-------------') |
| '''FRP配置''' |
| os.system("mkdir -p /content/frp") |
| os.system("wget /content/frp/frpc https://huggingface.co/Qilan2/box/resolve/main/frp/frpc -O /content/frp/frpc") |
| os.system("chmod +x /content/frp/frpc") |
| |
| with open(config_file_path, 'w') as config_file: |
| config_file.write(config_data1) |
| |
| frpc_cmd = ['/content/frp/frpc', '-c', config_file_path] |
| if backstage: |
| subprocess.Popen(frpc_cmd) |
| else: |
| subprocess.run(f'/content/frp/frpc -c {config_file_path}', shell=True, check=True) |
| print('-----------FPR结束-------------') |
| |
| |
| import requests |
| import re |
|
|
| def get_current_ip(): |
| """获取当前公共 IP 地址""" |
| response = requests.get("https://ipinfo.io/ip") |
| return response.text.strip() |
|
|
| def get_geo_info(ip_address): |
| """根据 IP 地址获取地理位置信息""" |
| url = f"https://api.qjqq.cn/api/Local" |
| headers = { |
| "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" |
| } |
| |
| response = requests.get(url, headers=headers) |
| |
| if response.status_code == 200: |
| geo_info = response.json() |
| |
| if geo_info['code'] == 200: |
| data = geo_info['data'] |
| return { |
| 'ip': data['ip'], |
| 'country': data['country'], |
| 'isp': data['isp'] |
| } |
| else: |
| print("无法获取地理位置信息") |
| return None |
| else: |
| print(f"请求失败, 状态码: {response.status_code}") |
| return None |
|
|
| def replace_ip_and_country_in_file(file_path): |
| try: |
| |
| ip_address = get_current_ip() |
| print(f"获取到当前 IP: {ip_address}") |
| |
| |
| geo_info = get_geo_info(ip_address) |
| |
| if geo_info is not None: |
| print(f"获取到地理信息: {geo_info}") |
| |
| |
| with open(file_path, 'r', encoding='utf-8') as file: |
| content = file.read() |
| |
| |
| |
| pattern = r'IP\[.*?\]国家\[.*?\]' |
| replacement = f'机子IP[{geo_info["ip"]}]国家[{geo_info["country"]}] ISP[{geo_info["isp"]}]' |
| new_content = re.sub(pattern, replacement, content) |
| |
| |
| |
| |
| with open(file_path, 'w', encoding='utf-8') as file: |
| file.write(new_content) |
| |
| print(f"成功更新为: IP[{geo_info['ip']}] 国家[{geo_info['country']}] ISP[{geo_info['isp']}]") |
| |
| except FileNotFoundError: |
| print(f"错误: 文件 {file_path} 不存在。") |
| except IOError as e: |
| print(f"IO 错误: {e}") |
| except Exception as e: |
| print(f"发生其他错误: {e}") |
|
|
|
|
|
|
| def SillyTavern(): |
| print('-----------SillyTavern开始-------------') |
| |
| os.system("mkdir -p ~/.kaggle") |
| file_path = '/root/.kaggle/kaggle.json' |
| with open(file_path, 'w') as json_file: |
| json.dump(ini_content, json_file, indent=4) |
| os.system("chmod 600 ~/.kaggle/kaggle.json") |
|
|
| clear_output() |
|
|
| os.system("rm -r /a /sillytavern /*.zi* /SillyTavern/") |
| os.system("mkdir -p /sillytavern") |
| os.chdir('/') |
| os.system("kaggle datasets download xovale7506/sillytavern-data") |
| |
| if not os.path.exists('/sillytavern-data.zip'): |
| print(f"文件 /sillytavern-data.zip 不存在,程序将结束。") |
| st_status = False |
| |
| print(f"文件 /sillytavern-data.zip 存在,继续执行程序。") |
| |
| os.system("7z x /sillytavern-data.zip -o/ -y") |
| os.system("mv /sillytavern.zip1 /sillytavern.zip") |
| os.system("7z x /sillytavern.zip -o/sillytavern -y") |
| os.system("rm *.zip") |
| clear_output() |
|
|
| |
| |
| |
| |
| |
| |
| |
| os.chdir('/sillytavern') |
| replace_ip_and_country_in_file('/sillytavern/public/login.html') |
| os.system("ls") |
| os.system("nvm install node") |
| os.system("nvm use node") |
| os.system("npm install -y") |
| try: |
| subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True) |
| except subprocess.CalledProcessError as e: |
| print(f"Command '{e.cmd}' returned non-zero exit status {e.returncode}.") |
| print("Output:", e.output) |
| os.chdir('/sillytavern') |
| subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True) |
| subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True) |
| subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True) |
| subprocess.run('yes | sh /sillytavern/start.sh', shell=True, check=True) |
| print('-----------SillyTavern结束-------------') |
| |
|
|
| |
| |
| |
| |
| threading.Thread(target=SillyTavern, daemon=True).start() |
| check_api1() |
| if not os.path.exists('/sillytavern-data.zip'): |
| |
| |
| |
| print("开始衔接") |
| Service_status = True |
| |
| |
| |
| frp_thread1 = threading.Thread(target=frp, args=(config_data2, '/content/frp/frpc2.ini', True)) |
| frp_thread1.start() |
| frp_thread2 = threading.Thread(target=frp, args=(config_data, '/content/frp/frpc.ini', False)) |
| frp_thread2.start() |
| while True: |
| if backup_thread.is_alive(): |
| print("备份线程仍在运行...") |
| else: |
| print("备份线程已停止.") |
| |
| |
| |
| try: |
| |
| subprocess.check_output(['pgrep', '-f', '/sillytavern/start.sh']) |
| |
| except subprocess.CalledProcessError: |
| print("脚本未运行。退出循环。") |
| compress_folder() |
| break |
| time.sleep(5) |
|
|
| else: |
| print("/sillytavern 文件不存在结束执行") |