注册 wispbyte

记得选 python.

在控制台记住 ip 和端口号,别忘了改代码里的信息。

然后

import os
import subprocess
import urllib.request
import zipfile
import json
import uuid
import stat
import time
import shutil

# --- 【配置区域】 ---
PORT = 10312                    # 端口
SERVER_IP = "x.x.x.x"   # 你的IP
TARGET_SNI = "www.microsoft.com" 
LINK_NAME = "My-Reality-Final"   
# --------------------

XRAY_DOWNLOAD_URL = "https://github.com/XTLS/Xray-core/releases/download/v1.8.4/Xray-linux-64.zip" 
# 注意:我锁定了一个稳定版本 v1.8.4,防止 latest 版本出幺蛾子
BIN_PATH = "./xray"
CONFIG_PATH = "./config.json"
KEY_INFO_FILE = "./node_info.json"

# --- 备用密钥 (万一生成失败就用这组,保证能启动) ---
FALLBACK_PRIVATE = "mMzV5L6X9J5t1Kj8oO-0z9J594tj599fj9gd1Kj8oO-0z9J5t1Kj8k"
FALLBACK_PUBLIC = "Z80rIqjV1e9XvJ9mK4lN6qR5sT49rj0j24trjddB89_8rJk7XFp"
# ------------------------------------------------

def force_cleanup():
    """强制清理旧文件"""
    print("正在清理环境...")
    try:
        if os.path.exists(BIN_PATH): os.remove(BIN_PATH)
        if os.path.exists("xray.zip"): os.remove("xray.zip")
        # 也要删除旧的密钥文件,防止读取到错误数据
        if os.path.exists(KEY_INFO_FILE): os.remove(KEY_INFO_FILE)
    except Exception as e:
        print(f"清理警告: {e}")

def download_xray():
    print(f"正在下载 Xray Core (v1.8.4) ...")
    zip_path = "xray.zip"
    try:
        opener = urllib.request.build_opener()
        opener.addheaders = [('User-agent', 'Mozilla/5.0')]
        urllib.request.install_opener(opener)
        urllib.request.urlretrieve(XRAY_DOWNLOAD_URL, zip_path)
        
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(".")
            
        st = os.stat(BIN_PATH)
        os.chmod(BIN_PATH, st.st_mode | stat.S_IEXEC)
        os.remove(zip_path)
        print("Xray 安装完成。")
    except Exception as e:
        print(f"❌ 下载失败: {e}")
        exit(1)

def get_keys():
    print("正在准备 Reality 密钥...")
    private_key = FALLBACK_PRIVATE
    public_key = FALLBACK_PUBLIC
    
    # 尝试生成新密钥
    try:
        process = subprocess.Popen([BIN_PATH, "x25519"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        stdout, stderr = process.communicate()
        
        if "Private key:" in stdout and "Public key:" in stdout:
            # 标准格式解析
            private_key = stdout.split("Private key:")[1].split("Public key:")[0].strip()
            public_key = stdout.split("Public key:")[1].strip()
            print("✅ 成功生成新密钥。")
        else:
            print("⚠️ 密钥生成输出格式异常,切换至【备用密钥】模式。")
            print(f"异常输出内容: {stdout}")
            
    except Exception as e:
        print(f"⚠️ 生成过程出错 ({e}),切换至【备用密钥】模式。")

    # 生成 UUID
    user_uuid = str(uuid.uuid4())
    short_id = "".join(list(map(lambda x: hex(x)[2:], os.urandom(4))))

    info = {
        "uuid": user_uuid,
        "private_key": private_key,
        "public_key": public_key,
        "short_id": short_id
    }
    
    # 保存
    with open(KEY_INFO_FILE, 'w') as f:
        json.dump(info, f, indent=4)
        
    return info

def create_config(info):
    config = {
        "log": {"loglevel": "warning"},
        "inbounds": [{
            "port": PORT,
            "protocol": "vless",
            "settings": {
                "clients": [{"id": info["uuid"], "flow": "xtls-rprx-vision"}],
                "decryption": "none"
            },
            "streamSettings": {
                "network": "tcp",
                "security": "reality",
                "realitySettings": {
                    "show": False,
                    "dest": f"{TARGET_SNI}:443",
                    "xver": 0,
                    "serverNames": [TARGET_SNI],
                    "privateKey": info["private_key"],
                    "shortIds": [info["short_id"]]
                }
            }
        }],
        "outbounds": [{"protocol": "freedom", "tag": "direct"}]
    }
    with open(CONFIG_PATH, "w") as f:
        json.dump(config, f, indent=4)
    print("配置文件已就绪。")

def print_share_link(info):
    link = (f"vless://{info['uuid']}@{SERVER_IP}:{PORT}"
            f"?security=reality&encryption=none&pbk={info['public_key']}"
            f"&headerType=none&fp=chrome&type=tcp&flow=xtls-rprx-vision"
            f"&sni={TARGET_SNI}&sid={info['short_id']}#{LINK_NAME}")
    
    print("\n" + "="*60)
    print(f"🚀 节点已启动!请复制下方链接:")
    print("-" * 20)
    print(link)
    print("-" * 20)
    print("="*60 + "\n")

def main():
    force_cleanup()
    download_xray()
    info = get_keys()
    create_config(info)
    print_share_link(info)
    
    print(f"正在启动 Xray Core (Port {PORT})...")
    sys_env = os.environ.copy()
    process = subprocess.Popen([BIN_PATH, "run", "-c", CONFIG_PATH], 
                               stdout=subprocess.PIPE, 
                               stderr=subprocess.STDOUT,
                               text=True,
                               env=sys_env)
    for line in process.stdout:
        print(line, end='')
    process.wait()

if __name__ == "__main__":
    main()

创建 main.py,把上面代码放进去并修改对应的信息,完事。
补一个测速。

值得点赞吗

如果赞够多我就再多研究一下


📌 转载信息
转载时间:
2025/12/30 15:30:22