You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 12:37:47