Spaces:
Paused
Paused
langchou commited on
Commit ·
835dd46
0
Parent(s):
init
Browse filesFiles changed (5)
- README.mdAdded+148
- parse.pyAdded+78
- requirements.txtAdded+2
- run_collector.pyAdded+132
- scheduler.pyAdded+113
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148# ProxyPool 代理池
这是一个简单的代理池项目,通过自动收集和验证代理,并提供统一的SOCKS5访问接口。项目包含两个主要功能:
1. 通过 aggregator 自动扫描和收集可用的代理服务器2. 使用 glider 将收集到的代理转换为统一的 SOCKS5 代理,供外部访问
## 功能特点
- 自动收集和更新代理- 定期检测代理可用性- 支持 SS 和 VMess 代理- 统一的 SOCKS5 访问接口- 自动故障转移
## 依赖要求
- Python 3.7+- glider
## 安装步骤
1. 克隆项目```bashgit clone <repository_url>cd proxyPool```
2. 安装 Python 依赖```bashpip install -r requirements.txt```
3. 安装 glider```bash# Linux/macOSwget https://github.com/nadoo/glider/releases/download/v0.16.3/glider_0.16.3_linux_amd64.tar.gztar -zxf glider_0.16.3_linux_amd64.tar.gzmv glider glider/chmod +x glider/glider```
## 项目结构
```proxyPool/├── aggregator/ # 代理收集模块├── glider/ # glider配置和可执行文件├── scheduler.py # 主调度器├── run_collector.py # 代理收集执行脚本└── parse.py # 配置解析脚本```
## 配置说明
1. 在 `aggregator/data/` 目录下会生成 `clash.yaml`,存储收集到的代理信息2. 在 `glider/` 目录下创建 `glider.conf` 配置文件,内容如下:
```conf# Verbose mode, print logsverbose=True
# 监听地址和端口listen=:10707
# Round Robin mode: rr# High Availability mode: hastrategy=rr
# forwarder health checkcheck=http://www.msftconnecttest.com/connecttest.txt#expect=200```
配置说明:- `verbose`: 是否打印详细日志- `listen`: 监听地址和端口,格式为 `[ip]:port`- `strategy`: 负载均衡策略 - `rr`: 轮询模式 - `ha`: 高可用模式- `check`: 健康检查配置 - 检查URL: `http://www.msftconnecttest.com/connecttest.txt` - 期望响应码: `200`
## 使用方法
1. 启动代理池服务```bashpython scheduler.py```
这个脚本会:- 启动 glider 代理服务器- 每30分钟自动更新一次代理池- 自动进行代理可用性检测
2. 手动更新代理池(可选)```bashpython run_collector.py```
3. 使用代理- 默认监听端口:10707- 协议:SOCKS5- 连接地址:127.0.0.1:10707
## 工作流程
1. `scheduler.py` - 作为主进程启动和管理整个服务 - 定期触发代理更新 - 管理 glider 进程
2. `run_collector.py` - 调用 aggregator 收集代理 - 生成 clash.yaml 配置文件 - 调用 parse.py 转换配置格式
3. `parse.py` - 将 clash 格式的配置转换为 glider 可用的格式 - 生成 glider.conf 配置文件
## 注意事项
1. 确保 glider 可执行文件位于正确位置2. 需要定期清理和更新代理池3. 建议配置自动启动脚本4. 如遇到问题,检查日志输出
## 常见问题
1. 如果代理无法连接,请检查: - glider 进程是否正常运行 - 代理池是否有可用代理 - 端口是否被占用
2. 如何修改监听端口? - 修改 glider.conf 中的 listen 配置
3. 如何添加自定义代理源? - 在 aggregator 模块中添加新的代理源
## 贡献指南
欢迎提交 Issue 和 Pull Request 来改进项目。
## 许可证
MIT License 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778import yamlimport jsonimport argparseimport sysfrom pathlib import Path
def parse_config(array: list): print(f"Debug: Received {len(array)} proxies to parse", file=sys.stderr) ss = [] vmess = [] # glider支持的ss加密方式 supported_ciphers = { 'aes-128-gcm', 'aes-256-gcm', 'chacha20-ietf-poly1305', 'aes-128-ctr', 'aes-192-ctr', 'aes-256-ctr', 'aes-128-cfb', 'aes-192-cfb', 'aes-256-cfb', 'chacha20-ietf', 'xchacha20-ietf-poly1305' }
for node in array: if node['type'] == 'ss': # 跳过不支持的加密方式 if node['cipher'] not in supported_ciphers: continue node_str = f"{node['type']}://{node['cipher']}:{node['password']}@{node['server']}:{node['port']}#{node['name']}" ss.append(node_str) elif node['type'] == 'vmess': node_str = f"{node['type']}://none:{node['uuid']}@{node['server']}:{node['port']}?alterID={node['alterId']}" vmess.append(node_str) # 构建输出内容 output = "" for node in ss: output += f'forward={node}\n' for node in vmess: output += f'forward={node}\n' return output
def main(): # 创建参数解析器 parser = argparse.ArgumentParser(description='Parse clash configuration file') parser.add_argument('config_path', help='Path to the clash.yaml configuration file') # 解析命令行参数 args = parser.parse_args() # 检查文件是否存在 config_path = Path(args.config_path) if not config_path.exists(): print(f"Error: File {args.config_path} does not exist", file=sys.stderr) sys.exit(1) try: # 读取并解析配置文件 with open(config_path, 'r', encoding='utf-8') as f: config = yaml.safe_load(f) if not config or 'proxies' not in config: print("Error: Invalid configuration file format", file=sys.stderr) sys.exit(1) output = parse_config(config['proxies']) print(output, end='') # 输出到标准输出,供run_collector.py捕获 except yaml.YAMLError as e: print(f"Error parsing YAML file: {e}", file=sys.stderr) sys.exit(1) except Exception as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1)
if __name__ == '__main__': main()
12pyyaml>=6.0.1requests>=2.31.0 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import subprocessimport sysimport osimport reimport yamlfrom pathlib import Path
def run_command(command, capture_output=False): try: process = subprocess.run( command, shell=True, check=True, stdout=subprocess.PIPE if capture_output else None, stderr=subprocess.PIPE, text=True ) return process.stdout if capture_output else True except subprocess.CalledProcessError as e: print(f"Error executing command: {command}") print(f"Error output: {e.stderr}") return False
def update_glider_conf(forward_content): current_dir = Path(__file__).parent.absolute() glider_conf_path = current_dir / "glider" / "glider.conf" # 基础配置 base_config = """# Verbose mode, print logsverbose=true
# 监听地址listen=:10707
# Round Robin mode: rr# High Availability mode: hastrategy=rr
# forwarder health checkcheck=http://www.msftconnecttest.com/connecttest.txt#expect=200
# check interval(seconds)checkinterval=30
""" # 确保glider目录存在 glider_dir = glider_conf_path.parent if not glider_dir.exists(): glider_dir.mkdir(parents=True) # 如果配置文件不存在,创建新文件 if not glider_conf_path.exists(): with open(glider_conf_path, 'w', encoding='utf-8') as f: f.write(base_config + forward_content) return # 读取现有配置文件 with open(glider_conf_path, 'r', encoding='utf-8') as f: content = f.read() # 检查是否存在forward配置 if re.search(r'forward=.*', content): # 替换所有现有的forward行 new_content = re.sub( r'(forward=.*\n)+', forward_content, content ) else: # 在文件末尾添加新的forward配置 new_content = content.rstrip() + '\n' + forward_content # 写入更新后的配置 with open(glider_conf_path, 'w', encoding='utf-8') as f: f.write(new_content)
def main(): # 获取当前脚本所在目录 current_dir = Path(__file__).parent.absolute() # 定义相关路径 collector_path = current_dir / "aggregator" / "subscribe" / "collect.py" parse_path = current_dir / "parse.py" # parse.py 现在和 run_collector.py 在同一目录 clash_yaml_path = current_dir / "aggregator" / "data" / "clash.yaml" # 确保 aggregator/data 目录存在 clash_yaml_path.parent.mkdir(parents=True, exist_ok=True) # 如果 clash.yaml 不存在,创建一个包含基本结构的文件 if not clash_yaml_path.exists(): initial_config = { 'proxies': [] } with open(clash_yaml_path, 'w', encoding='utf-8') as f: yaml.safe_dump(initial_config, f, allow_unicode=True) # 检查文件是否存在 if not collector_path.exists(): print(f"Error: Collector script not found at {collector_path}") sys.exit(1) if not parse_path.exists(): print(f"Error: Parser script not found at {parse_path}") sys.exit(1) # 1. 运行收集器脚本 print("Running collector...") # collect_command = f"python3 -u {collector_path} -s" # if not run_command(collect_command): # sys.exit(1) # 确认clash.yaml文件已生成 if not clash_yaml_path.exists(): print(f"Error: clash.yaml was not generated at {clash_yaml_path}") sys.exit(1) # 2. 运行解析器脚本并捕获输出 print("\nParsing collected data...") parse_command = f"python3 {parse_path} {clash_yaml_path}" forward_content = run_command(parse_command, capture_output=True) if not forward_content: sys.exit(1) # 3. 更新 glider.conf print("\nUpdating glider configuration...") update_glider_conf(forward_content) print("\nProcess completed successfully!")
if __name__ == "__main__": main() 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113import subprocessimport timeimport signalimport sysimport osfrom pathlib import Pathfrom datetime import datetime
def run_glider(glider_path, config_path): """启动glider进程""" try: process = subprocess.Popen( [glider_path, "-config", config_path], stdout=None, stderr=None, universal_newlines=True ) return process except Exception as e: print(f"Error starting glider: {e}") return None
def kill_glider(process): """终止glider进程""" if process: try: process.terminate() process.wait(timeout=5) # 等待进程终止 except subprocess.TimeoutExpired: process.kill() # 如果进程没有及时终止,强制结束 except Exception as e: print(f"Error killing glider: {e}")
def run_collector(): """运行收集器脚本""" try: subprocess.run(["python3", "run_collector.py"], check=True) return True except subprocess.CalledProcessError as e: print(f"Error running collector: {e}") return False
def main(): # 获取当前脚本所在目录 current_dir = Path(__file__).parent.absolute() glider_path = current_dir / "glider" / "glider" # glider可执行文件路径 config_path = current_dir / "glider" / "glider.conf" # 配置文件路径
# 检查必要文件是否存在 if not glider_path.exists(): print(f"Error: glider executable not found at {glider_path}") sys.exit(1)
# 确保glider可执行 glider_path.chmod(0o755)
# 初始化glider进程为None glider_process = None
def cleanup(signum, frame): """清理函数,用于处理终止信号""" print("\nReceived termination signal. Cleaning up...") if glider_process: kill_glider(glider_process) sys.exit(0)
# 注册信号处理器 signal.signal(signal.SIGTERM, cleanup) signal.signal(signal.SIGINT, cleanup)
try: # 首先启动glider进程 print(f"\n[{datetime.now()}] Starting initial glider process...") glider_process = run_glider(str(glider_path), str(config_path)) if not glider_process: print("Failed to start initial glider process") sys.exit(1) print("Initial glider process started successfully")
# 然后进入主循环 while True: # 等待30分钟 print(f"[{datetime.now()}] Waiting 30 minutes until next update...") time.sleep(1800) # 30分钟 = 1800秒 print(f"\n[{datetime.now()}] Starting update cycle...") # 运行收集器 if run_collector(): # 如果glider正在运行,先终止它 if glider_process: print("Stopping current glider process...") kill_glider(glider_process)
# 启动新的glider进程 print("Starting new glider process...") glider_process = run_glider(str(glider_path), str(config_path)) if not glider_process: print("Failed to start glider") continue
print("Update completed successfully") else: print("Collector failed, keeping current glider process")
except KeyboardInterrupt: print("\nReceived keyboard interrupt. Cleaning up...") if glider_process: kill_glider(glider_process) sys.exit(0)
if __name__ == "__main__": main()README.mdAdded+148
parse.pyAdded+78
requirements.txtAdded+2
run_collector.pyAdded+132
scheduler.pyAdded+113