File size: 9,386 Bytes
8c6d807
 
 
 
 
 
 
4318959
12412ba
8c6d807
 
 
 
 
12412ba
676a0c7
8c6d807
 
 
 
 
12412ba
8c6d807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12412ba
8c6d807
 
12412ba
8c6d807
 
 
 
 
 
 
12412ba
8c6d807
 
12412ba
8c6d807
 
 
 
 
 
 
 
12412ba
8c6d807
 
12412ba
8c6d807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
def55e0
8c6d807
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import requests
import subprocess
import threading
import shutil
import zipfile
import os
import time
import json



huggiingface_repo_id = 'Qi28/SD_QZ'  # Hugging Face 数据集 ID
huggiingface_path = 'frp'
download_path = '/tmp/code/frp' 
frp_status = False #是否启用frp, 0 否 1 是
nps_status = True #是否启用nps, 0 否 1 是
sd_url = 'http://119.8.118.149:8000'
NPS_key = 'q9wj1cnlek4j3hg5'
NPS_server = '119.8.118.149:7001'
nezha_agent_key = 'L3USpU8bbpHRV90uuC'
nezha_agent_url = 'nzzz.nwb.lol:5555'
print(frp_status)

#!export CUDA_VISIBLE_DEVICES=0,1


def Frpc():
    thread = threading.Thread(target=run_commands)
    thread.start()
    os.system('rm /tmp/code/frp/*.ini')
    # 定义 Hugging Face 数据集 ID
    api_url = f'https://hf-mirror.com/api/datasets/{huggiingface_repo_id}/tree/main/{huggiingface_path}' 

    # 获取文件列表
    response = requests.get(api_url)
    if response.status_code != 200:
        print(f'Error: Failed to fetch file list from {api_url}')
        response.raise_for_status()

    file_list = response.json()
    yun_files = [file['path'] for file in file_list if file['type'] == 'file']

    # 下载文件
    for yun_file in yun_files:
        url = f'https://hf-mirror.com/datasets/{huggiingface_repo_id}/resolve/main/{yun_file}' 
        response = requests.head(url)
        if response.status_code == 200:
            result = subprocess.run(['wget', '-O', os.path.join(download_path, os.path.basename(yun_file)), url, '-q'], capture_output=True)
            if result.returncode != 0:
                print(f'Error: Failed to download {yun_file} from {url}')
        else:
            print(f'Error: Invalid URL {url}')

    frpc_executable = '/tmp/code/frp/frpc'
    subprocess.run(['chmod', '+x', frpc_executable], check=True)

    # 启动 frpc 实例
    for yun_file in yun_files:
        frpini_path = os.path.join(download_path, os.path.basename(yun_file))
        print(f'运行FRP配置: {frpini_path}')
        subprocess.Popen([frpc_executable, '-c', frpini_path])


def NPS():
    os.system("/tmp/code/nps/npc -server={NPS_server} -vkey={NPS_key} -type=tcp")

def run_commands():
    run_command("apt update")
    run_command("apt install openssh-server -y")
    run_command("apt-get install vim -y")
    config_client_cmd = "sed -i '/PasswordAuthentication/s/^#//g' /etc/ssh/ssh_config"
    run_command(config_client_cmd)
    config_server_cmd = "sed -i '/PermitRootLogin prohibit-password/s/prohibit-password/yes/' /etc/ssh/sshd_config"
    run_command(config_server_cmd)
    run_command("systemctl restart ssh")
    os.system("echo 'root:qilan' | chpasswd")
    os.system("echo 'PermitRootLogin yes' | 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 ':') ")

def run_command(command):
    try:
        subprocess.run(command, check=True, shell=True)
    except subprocess.CalledProcessError as e:
        print(f"An error occurred: {e}")



def run_script():
    os.system('rm -r /tmp/code/nezha-agent')
    # GitHub项目名和API URL
    project_name = "nezhahq/agent"
    releases_api_url = f"https://api.github.com/repos/{project_name}/releases"
    # 获取最新版本的信息
    response = requests.get(releases_api_url)
    if response.status_code == 200:
        releases = response.json()
        latest_version = releases[0]['tag_name']  # 假设最新版本是列表中的第一个
        print(f"Latest version: {latest_version}")
    else:
        print("Failed to fetch releases information.")
        exit()
    # 构造下载链接
    download_url = f"https://slink.ltd/https://github.com/{project_name}/releases/download/{latest_version}/nezha-agent_linux_amd64.zip"
    # 指定下载文件的保存路径
    zip_file_path = "/tmp/code/nezha-agent.zip"  # 临时ZIP文件路径
    # 确保下载目录存在
    os.makedirs(os.path.dirname(zip_file_path), exist_ok=True)
    # 发送HTTP GET请求下载文件
    response = requests.get(download_url, stream=True)
    # 检查请求是否成功
    if response.status_code == 200:
        # 打开文件进行写入
        with open(zip_file_path, 'wb') as file:
            for chunk in response.iter_content(chunk_size=128):
                file.write(chunk)
        print(f"Download completed. File saved to {zip_file_path}")
        # 解压ZIP文件
        with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
            zip_ref.extractall("/tmp/code/")
        print("Extraction completed.")
        os.remove(zip_file_path)
        print(f"Removed temporary zip file: {zip_file_path}")
    else:
        print(f"Failed to download the file. Status code: {response.status_code}")
        print('启动哪吒面板')
    try:
        subprocess.run(["chmod", "+x", "/tmp/code/nezha-agent"], check=True)
        subprocess.run(["/tmp/code/nezha-agent", "-s", "nzzz.nwb.lol:5555", "-p", nezha_agent_key, "-d"], check=True)
    except subprocess.CalledProcessError as e:
        print(f"启动哪吒面板失败,错误内容: {e}") 

# 等待启动穿透
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():
    while True:
        try:
            url = "http://127.0.0.1:7860/sdapi/v1/txt2img"
            response = requests.get(url, timeout=30)
            try:
                response_json = response.json()
                if response_json.get("detail") in ("Method Not Allowed", "Not Found"):
                    print("SD已经启动")
                    break  # 接口正常,退出循环
                else:
                    print("SD未启动" )
            except json.JSONDecodeError:
                # 如果响应内容不是有效的 JSON,打印错误信息
                print("SD未启动2")
        except requests.exceptions.RequestException as e:
            print("SD未启动3")
        time.sleep(5)
    print('开始检测接口状态')
    while True:
        url = f"{sd_url}/sdapi/v1/txt2img" 
        try:
            response = requests_retry_session().get(url, timeout=30)
            response.raise_for_status() 
            response_json = response.json()
            if "detail" in response_json and response_json["detail"] in ("Method Not Allowed", "Not Found"):
                print("接口正常")
            else:
                print("接口返回信息:", response_json)
        except requests.exceptions.HTTPError as e:
            print("接口正常2")
        except requests.exceptions.ConnectionError as e:
            print(f"接口异常1: {e}")
            if frp_status:
                print("启动FRP")
                threading.Thread(target=Frpc, daemon=True).start()
            if nps_status:
                print("启动NPS")
                threading.Thread(target=NPS, daemon=True).start()
            # threading.Thread(target=run_script).start()
            #threading.Thread(target=run_commands).start()
            break
        except requests.exceptions.Timeout as e:
            print(f"接口异常2: {e}")
            if frp_status:
                print("启动FRP")
                threading.Thread(target=Frpc, daemon=True).start()
            if nps_status:
                print("启动NPS")
                threading.Thread(target=NPS, daemon=True).start()
            # threading.Thread(target=run_script).start()
            #threading.Thread(target=run_commands).start()
            break
            
        except requests.exceptions.RequestException as e:
            print(f"接口异常3: {e}")
            if frp_status:
                print("启动FRP")
                threading.Thread(target=Frpc, daemon=True).start()
            if nps_status:
                print("启动NPS")
                threading.Thread(target=NPS, daemon=True).start()
            # threading.Thread(target=run_script).start()
            #threading.Thread(target=run_commands).start()
            break
        time.sleep(5)
threading.Thread(target=check_api1, daemon=True).start()

def comfyui():
    subprocess.run(["python", "/tmp/code/sd/ComfyUI/main.py"], check=True)
def server():
    os.system('mr -r /tmp/code/main.py')
    os.system("wget -O /tmp/code/main.py 'https://hf-mirror.com/datasets/Qi28/SD_QZ/resolve/main/main.py'")
    subprocess.run(["python", "/tmp/code/main.py"], check=True)
threading.Thread(target=run_commands).start()
threading.Thread(target=server, daemon=True).start()
threading.Thread(target=comfyui, daemon=True).start()
os.system('rm /tmp/code/sd/stable-diffusion-webui/config.json /tmp/code/*.log')
os.system("wget -O /tmp/code/sd/stable-diffusion-webui/config.json 'https://hf-mirror.com/datasets/Qi28/SD_QZ/resolve/main/comfig/sd_config.json'")
# python /tmp/code/sd/stable-diffusion-webui/launch.py  --api --api-auth QiLan:1415361185 --no-hashing --enable-insecure-extension-access --no-gradio-queue --no-half-vae --port 7860 --xformers 
os.system("python /tmp/code/sd/stable-diffusion-webui/launch.py")