如何通过Python启动ngrok并自动复制公网链接?
实现Python脚本启动ngrok并复制公网链接
核心方案
ngrok启动后会在本地提供API服务(默认地址http://127.0.0.1:4040),通过调用/api/tunnels接口可直接获取隧道的公网链接,比解析命令行输出更可靠。我们可以用subprocess后台启动ngrok,再通过API提取链接并复制到剪贴板。
完整代码示例
import subprocess import time import requests import pyperclip import sys def start_ngrok_and_copy_url(port=80): # 后台启动ngrok进程 try: ngrok_process = subprocess.Popen( ["ngrok", "http", str(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) except FileNotFoundError: print("错误:未找到ngrok,请确保其已添加到系统PATH") sys.exit(1) # 等待ngrok初始化API服务 time.sleep(3) # 调用API获取隧道信息 try: response = requests.get("http://127.0.0.1:4040/api/tunnels") response.raise_for_status() tunnels = response.json()["tunnels"] except requests.exceptions.RequestException: print("错误:无法连接ngrok API,请检查进程是否正常启动") ngrok_process.terminate() sys.exit(1) # 提取HTTPS公网链接(优先选HTTPS,也可改为HTTP) public_url = None for tunnel in tunnels: if tunnel["proto"] == "https": public_url = tunnel["public_url"] break if not public_url: print("错误:未找到可用的HTTP/HTTPS隧道") ngrok_process.terminate() sys.exit(1) # 复制到剪贴板 pyperclip.copy(public_url) print(f"ngrok公网链接已复制:{public_url}") # 保持脚本运行,防止ngrok进程被终止(可根据需求删除) try: ngrok_process.wait() except KeyboardInterrupt: print("\nngrok进程已终止") ngrok_process.terminate() if __name__ == "__main__": start_ngrok_and_copy_url()
关键注意点
- 先安装依赖:执行
pip install requests pyperclip - 确保ngrok已安装并加入系统PATH,或在代码中指定完整路径(如
["C:/tools/ngrok.exe", "http", "80"]) time.sleep(3)可根据实际启动速度调整,避免API未就绪就请求- 如需指定端口,调用
start_ngrok_and_copy_url(port=5000)即可
内容的提问来源于stack exchange,提问作者swanenjoyer
相关产品推荐
相关产品推荐

