warp-proxy-test-1769392021 / generate_pool.py
cefrefdwe's picture
Upload WARP proxy tool with offline IP pool
d919696 verified
Raw History Blame Contribute Delete
4.73 kB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WARP IP 池生成器 (本地工厂模式)
功能:批量注册 WARP 账号,生成 ip_pool.json,供 HF 容器使用。
"""
import os
import sys
import json
import time
import subprocess
import logging
import platform
# 配置
POOL_SIZE = 5 # 演示用,生成 5 个账号
OUTPUT_FILE = "ip_pool.json"
BIN_DIR = "bin"
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
logger = logging.getLogger("IP-FACTORY")
def get_wgcf_binary():
"""获取或下载 wgcf"""
system = platform.system().lower()
machine = platform.machine().lower()
if system == "darwin":
if machine == "arm64":
url = "https://github.com/ViRb3/wgcf/releases/download/v2.2.22/wgcf_2.2.22_darwin_arm64"
else:
url = "https://github.com/ViRb3/wgcf/releases/download/v2.2.22/wgcf_2.2.22_darwin_amd64"
elif system == "linux":
url = "https://github.com/ViRb3/wgcf/releases/download/v2.2.22/wgcf_2.2.22_linux_amd64"
else:
logger.error(f"不支持的系统: {system}")
sys.exit(1)
binary_path = os.path.join(BIN_DIR, "wgcf")
if not os.path.exists(BIN_DIR):
os.makedirs(BIN_DIR)
if not os.path.exists(binary_path):
logger.info(f"正在下载 wgcf: {url}")
subprocess.run(["curl", "-L", "-o", binary_path, url], check=True)
subprocess.run(["chmod", "+x", binary_path], check=True)
return binary_path
def parse_profile(conf_path):
"""解析 wgcf-profile.conf 提取关键信息"""
if not os.path.exists(conf_path):
return None
data = {}
with open(conf_path, 'r') as f:
for line in f:
line = line.strip()
if line.startswith("PrivateKey"):
data['private_key'] = line.split("=")[1].strip()
elif line.startswith("Address"):
# 通常有两个地址,我们取 IPv6 (第二个) 或者都存
# 示例: Address = 172.16.0.2/32, 2606:4700:110:8f6a:XXXX/128
addrs = line.split("=")[1].strip().split(",")
data['address_v4'] = addrs[0].strip()
if len(addrs) > 1:
data['address_v6'] = addrs[1].strip()
elif line.startswith("PublicKey"):
data['public_key'] = line.split("=")[1].strip()
return data
def generate_account(wgcf_bin, index):
"""生成单个账号"""
logger.info(f"[{index}/{POOL_SIZE}] 正在注册新账号...")
# 清理旧文件
for f in ["wgcf-account.toml", "wgcf-profile.conf"]:
if os.path.exists(f):
os.remove(f)
try:
# 1. 注册 (增加重试机制)
max_retries = 3
for attempt in range(max_retries):
try:
subprocess.run([wgcf_bin, "register", "--accept-tos"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
break
except subprocess.CalledProcessError:
if attempt < max_retries - 1:
logger.warning(f"⚠️ 注册失败,正在重试 ({attempt + 1}/{max_retries})...")
time.sleep(2)
else:
logger.error("❌ 注册失败,跳过此账号")
return None
# 2. 生成配置
subprocess.run([wgcf_bin, "generate"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# 3. 解析
profile = parse_profile("wgcf-profile.conf")
if profile:
logger.info(f"✅ 账号 {index} 生成成功")
return profile
else:
logger.error(f"❌ 账号 {index} 解析失败")
return None
except Exception as e:
logger.error(f"❌ 账号 {index} 生成出错: {e}")
return None
def main():
wgcf_bin = get_wgcf_binary()
accounts = []
logger.info("🚀 开始生成 IP 池...")
for i in range(1, POOL_SIZE + 1):
acc = generate_account(wgcf_bin, i)
if acc:
acc['id'] = i
acc['created_at'] = time.time()
accounts.append(acc)
# 避免请求过快
time.sleep(2)
# 保存结果
with open(OUTPUT_FILE, 'w') as f:
json.dump(accounts, f, indent=2)
logger.info(f"🎉 完成!已生成 {len(accounts)} 个账号,保存在 {OUTPUT_FILE}")
# 清理临时文件
for f in ["wgcf-account.toml", "wgcf-profile.conf"]:
if os.path.exists(f):
os.remove(f)
if __name__ == "__main__":
main()