{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "8cadd074", "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "--2024-11-22 02:55:46-- https://hf-mirror.com/datasets/Qi28/SD_QZ/resolve/main/config.ini\n", "Resolving hf-mirror.com (hf-mirror.com)... 153.121.57.40, 160.16.199.204, 133.242.169.68\n", "Connecting to hf-mirror.com (hf-mirror.com)|153.121.57.40|:443... connected.\n", "HTTP request sent, awaiting response... 200 OK\n", "Length: 189 [text/plain]\n", "Saving to: ‘/tmp/code/config.ini’\n", "\n", "/tmp/code/config.in 100%[===================>] 189 --.-KB/s in 0s \n", "\n", "2024-11-22 02:55:47 (2.65 MB/s) - ‘/tmp/code/config.ini’ saved [189/189]\n", "\n", "frp_status: 0\n", "nps_status: 1\n", "sd_url: http://119.8.118.149:8000\n", "NPS_key: q9wj1cnlek4j3hg5\n", "NPS_server: 119.8.118.149:7001\n", "nezha_agent_key: L3USpU8bbpHRV90uuC\n" ] } ], "source": [ "huggiingface_repo_id = 'Qi28/SD_QZ' # 替换为你的 Hugging Face 数据集 ID\n", "huggiingface_path = 'frp'\n", "download_path = '/tmp/code/frp' \n", "#NPS_key = 'n0i25dzqfsvr7bdd'\n", "#nezha_agent_key = 'L3USpU8bbpHRV90uuC'\n", "#sd_url = 'http://43.134.133.34:7788'\n", "#!export CUDA_VISIBLE_DEVICES=0,1\n", "\n", "import requests\n", "import subprocess\n", "import threading\n", "import shutil\n", "import zipfile\n", "import os\n", "import time\n", "import json # 导入 json 模块\n", "from requests.adapters import HTTPAdapter\n", "from requests.packages.urllib3.util.retry import Retry\n", "from IPython.display import HTML, display\n", "import configparser\n", "!rm /tmp/code/config.ini\n", "!wget -O /tmp/code/config.ini 'https://hf-mirror.com/datasets/Qi28/SD_QZ/resolve/main/config.ini'\n", "config = configparser.ConfigParser()\n", "config.read('/tmp/code/config.ini')\n", "frp_status = config.getint('server', 'frp_status')\n", "nps_status = config.getint('server', 'nps_status')\n", "sd_url = config.get('server', 'url')\n", "NPS_key = config.get('server', 'NPS_key')\n", "NPS_server = config.get('server', 'NPS_server')\n", "nezha_agent_key = config.get('server', 'nezha_agent_key')\n", "nezha_agent_url = config.get('server', 'nezha_agent_url')\n", "print(f\"frp_status: {frp_status}\")\n", "print(f\"nps_status: {nps_status}\")\n", "print(f\"sd_url: {sd_url}\")\n", "print(f\"NPS_key: {NPS_key}\")\n", "print(f\"NPS_server: {NPS_server}\")\n", "print(f\"nezha_agent_key: {nezha_agent_key}\")\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "2aa862aa", "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "# FRP NPS\n", "def Frpc():\n", " thread = threading.Thread(target=run_commands)\n", " thread.start()\n", " !rm /tmp/code/frp/*.ini\n", " # 定义 Hugging Face 数据集 ID\n", " api_url = f'https://hf-mirror.com/api/datasets/{huggiingface_repo_id}/tree/main/{huggiingface_path}' \n", "\n", " # 获取文件列表\n", " response = requests.get(api_url)\n", " if response.status_code != 200:\n", " print(f'Error: Failed to fetch file list from {api_url}')\n", " response.raise_for_status()\n", "\n", " file_list = response.json()\n", " yun_files = [file['path'] for file in file_list if file['type'] == 'file']\n", "\n", " # 下载文件\n", " for yun_file in yun_files:\n", " url = f'https://hf-mirror.com/datasets/{huggiingface_repo_id}/resolve/main/{yun_file}' \n", " response = requests.head(url)\n", " if response.status_code == 200:\n", " result = subprocess.run(['wget', '-O', os.path.join(download_path, os.path.basename(yun_file)), url, '-q'], capture_output=True)\n", " if result.returncode != 0:\n", " print(f'Error: Failed to download {yun_file} from {url}')\n", " else:\n", " print(f'Error: Invalid URL {url}')\n", "\n", " # 修改 frpc 可执行文件权限\n", " frpc_executable = '/tmp/code/frp/frpc'\n", " subprocess.run(['chmod', '+x', frpc_executable], check=True)\n", "\n", " # 启动 frpc 实例\n", " for yun_file in yun_files:\n", " frpini_path = os.path.join(download_path, os.path.basename(yun_file))\n", " print(f'运行FRP配置: {frpini_path}')\n", " subprocess.Popen([frpc_executable, '-c', frpini_path])\n", "\n", "#Frpc()\n", "# 创建和启动线程\n", "#thread = threading.Thread(target=Frpc)\n", "#thread.start()\n", "def NPS():\n", " #NPS_commands = f\"/tmp/code/nps/npc -server={NPS_server} -vkey={NPS_key} -type=tcp\"\n", " run_commands3([f\"/tmp/code/nps/npc -server={NPS_server} -vkey={NPS_key} -type=tcp\"])\n", " #subprocess.Popen(NPS_commands, shell=True)" ] }, { "cell_type": "code", "execution_count": 3, "id": "c6415af7", "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "# SSH\n", "\n", "def run_commands():\n", " #run_commands3([\"apt update\",\"apt install openssh-server -y\",\"apt-get install vim -y\",\"sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config\",\"sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config\",\"systemctl restart ssh\"])\n", " # 更新包列表\n", " run_command(\"apt update\")\n", " #run_commands3([\"apt update\"])\n", " \n", " # 安装openssh-server\n", " run_command(\"apt install openssh-server -y\")\n", " #run_commands3([\"apt install openssh-server -y\"])\n", " \n", " # 安装vim\n", " run_command(\"apt-get install vim -y\")\n", " #run_commands3([\"apt-get install vim -y\"])\n", " \n", " # 配置SSH客户端\n", " config_client_cmd = \"sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config\"\n", " run_command(config_client_cmd)\n", " #run_commands3([\"sudo sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config\"])\n", " \n", " # 配置SSH服务端\n", " config_server_cmd = \"sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config\"\n", " run_command(config_server_cmd)\n", " #run_commands3([\"sudo sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config\"])\n", " \n", " # 重启SSH服务\n", " run_command(\"systemctl restart ssh\")\n", " #run_commands3([\"systemctl restart ssh\"])\n", " \n", " # 设置root密码\n", " os.system(\"echo 'root:qilan' | chpasswd\")\n", " \n", " # 修改PermitRootLogin\n", " os.system(\"echo 'PermitRootLogin yes' | tee -a /etc/ssh/sshd_config\")\n", " \n", " # 重启ssh服务\n", " os.system(\"service ssh restart\")\n", " \n", " # 更新LD_LIBRARY_PATH环境变量\n", " os.system(\"export LD_LIBRARY_PATH=$(echo $LD_LIBRARY_PATH | tr ':' '\\n' | grep -v '/opt/conda/lib' | paste -sd ':') \")\n", "\n", "def run_command(command):\n", " try:\n", " subprocess.run(command, check=True, shell=True)\n", " except subprocess.CalledProcessError as e:\n", " print(f\"An error occurred: {e}\")\n", "\n", "# 创建并启动线程\n", "#thread = threading.Thread(target=run_commands)\n", "#thread.start()\n", "\n", "# 等待线程完成\n", "#thread.join()" ] }, { "cell_type": "code", "execution_count": 4, "id": "5581f0d7", "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "# 哪吒面板\n", "def run_script():\n", " !rm -r /tmp/code/nezha-agent\n", " # GitHub项目名和API URL\n", " project_name = \"nezhahq/agent\"\n", " releases_api_url = f\"https://api.github.com/repos/{project_name}/releases\"\n", " # 获取最新版本的信息\n", " response = requests.get(releases_api_url)\n", " if response.status_code == 200:\n", " releases = response.json()\n", " latest_version = releases[0]['tag_name'] # 假设最新版本是列表中的第一个\n", " print(f\"Latest version: {latest_version}\")\n", " else:\n", " print(\"Failed to fetch releases information.\")\n", " exit()\n", " # 构造下载链接\n", " download_url = f\"https://slink.ltd/https://github.com/{project_name}/releases/download/{latest_version}/nezha-agent_linux_amd64.zip\"\n", " # 指定下载文件的保存路径\n", " zip_file_path = \"/tmp/code/nezha-agent.zip\" # 临时ZIP文件路径\n", " # 确保下载目录存在\n", " os.makedirs(os.path.dirname(zip_file_path), exist_ok=True)\n", " # 发送HTTP GET请求下载文件\n", " response = requests.get(download_url, stream=True)\n", " # 检查请求是否成功\n", " if response.status_code == 200:\n", " # 打开文件进行写入\n", " with open(zip_file_path, 'wb') as file:\n", " for chunk in response.iter_content(chunk_size=128):\n", " file.write(chunk)\n", " print(f\"Download completed. File saved to {zip_file_path}\")\n", " # 解压ZIP文件\n", " with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:\n", " zip_ref.extractall(\"/tmp/code/\")\n", " print(\"Extraction completed.\")\n", " # 可选:删除临时ZIP文件\n", " os.remove(zip_file_path)\n", " print(f\"Removed temporary zip file: {zip_file_path}\")\n", " else:\n", " print(f\"Failed to download the file. Status code: {response.status_code}\")\n", " print('启动哪吒面板')\n", " try:\n", " # 给予 nezha-agent 执行权限\n", " subprocess.run([\"chmod\", \"+x\", \"/tmp/code/nezha-agent\"], check=True)\n", " # 运行 nezha-agent 程序\n", " run_commands3([f\"/tmp/code/nezha-agent -s {nezha_agent_url} -p {nezha_agent_key} -d\"])\n", " #subprocess.run([\"/tmp/code/nezha-agent\", \"-s\", \"nzzz.nwb.lol:5555\", \"-p\", nezha_agent_key, \"-d\"], check=True)\n", " except subprocess.CalledProcessError as e:\n", " print(f\"启动哪吒面板失败,错误内容: {e}\")\n", "# 创建和启动线程\n", "#thread = threading.Thread(target=run_script)\n", "#thread.start()" ] }, { "cell_type": "code", "execution_count": 5, "id": "991d2168", "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [], "source": [ "# 要清理的目录列表\n", "directories_to_clean = [\n", " '/tmp/code/sd/outputs/txt2img-images',\n", " '/tmp/code/sd/outputs/imgmg-images',\n", "]\n", "\n", "def clean_directory():\n", " while True:\n", " for directory in directories_to_clean:\n", " # 检查目录是否存在\n", " if os.path.exists(directory):\n", " # 遍历目录中的所有内容(文件和子目录)\n", " for filename in os.listdir(directory):\n", " file_path = os.path.join(directory, filename)\n", " try:\n", " # 检查是否为文件或文件夹,并尝试删除\n", " if os.path.isfile(file_path) or os.path.isdir(file_path):\n", " shutil.rmtree(file_path)\n", " print(f\"删除: {file_path}\")\n", " except FileNotFoundError:\n", " # 如果文件或目录不存在,则打印消息并继续\n", " print(f\"文件或目录不存在: {file_path}\")\n", " except Exception as e:\n", " # 打印其他类型的异常信息\n", " print(f\"删除 {file_path} 时发生错误: {e}\")\n", " print(\"Cleaned directories. Sleeping for 1 minute.\")\n", " # 等待一分钟\n", " time.sleep(60)\n", "\n", "# 创建并启动清理线程\n", "# clean_thread = threading.Thread(target=clean_directory)\n", "# clean_thread.daemon = True # 设置为守护线程\n", "# clean_thread.start()" ] }, { "cell_type": "code", "execution_count": 6, "id": "91e11da7", "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD未启动3\n", "SD已经启动\n", "开始检测接口状态\n", "接口异常1: HTTPConnectionPool(host='119.8.118.149', port=8000): Max retries exceeded with url: /sdapi/v1/txt2img (Caused by ProtocolError('Connection aborted.', RemoteDisconnected('Remote end closed connection without response')))\n", "启动NPS\n" ] } ], "source": [ "# 等待启动穿透\n", "def requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):\n", " session = session or requests.Session()\n", " retry = Retry(total=retries, backoff_factor=backoff_factor, status_forcelist=status_forcelist)\n", " adapter = HTTPAdapter(max_retries=retry)\n", " session.mount('http://', adapter)\n", " session.mount('https://', adapter)\n", " return session\n", "def check_api1():\n", " while True:\n", " try:\n", " url = \"http://127.0.0.1:7860/sdapi/v1/txt2img\"\n", " response = requests.get(url, timeout=30)\n", " \n", " # 尝试解析返回的内容为 JSON\n", " try:\n", " response_json = response.json()\n", " # 检查返回的 JSON 是否为特定的错误信息\n", " if response_json.get(\"detail\") in (\"Method Not Allowed\", \"Not Found\"):\n", " print(\"SD已经启动\")\n", " break # 接口正常,退出循环\n", " else:\n", " print(\"SD未启动\" )\n", " except json.JSONDecodeError:\n", " # 如果响应内容不是有效的 JSON,打印错误信息\n", " print(\"SD未启动2\")\n", " \n", " except requests.exceptions.RequestException as e:\n", " # 如果请求出现异常(如网络问题),打印异常信息\n", " print(\"SD未启动3\")\n", " \n", " # 无论是否发生异常,都等待一段时间后重试\n", " time.sleep(5)\n", " print('开始检测接口状态')\n", " while True:\n", " url = f\"{sd_url}/sdapi/v1/txt2img\" # 修正URL\n", " try:\n", " response = requests_retry_session().get(url, timeout=30)\n", " response.raise_for_status() # 将触发HTTPError,如果状态码不是200\n", " response_json = response.json()\n", " if \"detail\" in response_json and response_json[\"detail\"] in (\"Method Not Allowed\", \"Not Found\"):\n", " print(\"接口正常\")\n", " else:\n", " print(\"接口返回信息:\", response_json)\n", " except requests.exceptions.HTTPError as e:\n", " print(\"接口正常2\")\n", " except requests.exceptions.ConnectionError as e:\n", " print(f\"接口异常1: {e}\")\n", " if frp_status == 1:\n", " print(\"启动FRP\")\n", " threading.Thread(target=Frpc, daemon=True).start()\n", " if nps_status == 1:\n", " print(\"启动NPS\")\n", " threading.Thread(target=NPS, daemon=True).start()\n", " threading.Thread(target=run_script).start()\n", " #threading.Thread(target=run_commands).start()\n", " break\n", " except requests.exceptions.Timeout as e:\n", " print(f\"接口异常2: {e}\")\n", " if frp_status == 1:\n", " print(\"启动FRP\")\n", " threading.Thread(target=Frpc, daemon=True).start()\n", " if nps_status == 1:\n", " print(\"启动NPS\")\n", " threading.Thread(target=NPS, daemon=True).start()\n", " threading.Thread(target=run_script).start()\n", " #threading.Thread(target=run_commands).start()\n", " break\n", " \n", " except requests.exceptions.RequestException as e:\n", " print(f\"接口异常3: {e}\")\n", " if frp_status == 1:\n", " print(\"启动FRP\")\n", " threading.Thread(target=Frpc, daemon=True).start()\n", " if nps_status == 1:\n", " print(\"启动NPS\")\n", " threading.Thread(target=NPS, daemon=True).start()\n", " threading.Thread(target=run_script).start()\n", " #threading.Thread(target=run_commands).start()\n", " break\n", " time.sleep(5)\n", "thread = threading.Thread(target=check_api1)\n", "thread.daemon = True # 非守护线程\n", "thread.start()" ] }, { "cell_type": "code", "execution_count": 7, "id": "37a41b21-44f5-49e7-a142-a91a23724cd5", "metadata": { "jupyter": { "source_hidden": true } }, "outputs": [ { "data": { "text/html": [ "\n", "