在一台设备上使用多个ngrok账号
ngrok一个免费账号只能使用一个代理,如果要进行多个代理转发,可以使用多个账号。
查询ngrok官方文档可以知道:ngrok启动时会读取ngrok.yml
配置文件,配置文件中存储了authtoken信息,一个authtoken对应一个账号。可以使用参数指定读取的配置文件。
python脚本和目录结构如下
1 2 3 4 5 6
| . ├── main.py ├── ngrok1.yml ├── ngrok2.yml ├── ngrok3.yml ├── ngrok4.yml
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import subprocess import threading import time
def print_output(proc, name): for line in proc.stdout: if "started tunnel" in line: print(f"[{name}] {line.strip()}")
def start_ngrok(): procs = [] names = ["service1", "service2", "service3", "service4"] configs = ["ngrok1.yml", "ngrok2.yml", "ngrok3.yml", "ngrok4.yml"] ports = ["19000", "19001", "19002", "19003"]
for name, config, port in zip(names, configs, ports): p = subprocess.Popen( ["ngrok", "tcp", port, "--config", config, "--log", "stdout"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True ) procs.append(p) threading.Thread(target=print_output, args=(p, name), daemon=True).start()
try: while True: time.sleep(1) except KeyboardInterrupt: print("Ctrl+C detected, killing all ngrok processes...") finally: subprocess.run(["killall", "ngrok"])
if __name__ == "__main__": start_ngrok()
|
运行python main.py
,会启动4个ngrok进程,每个进程使用不同的配置文件。
效果如下:
1 2 3
| [service2] t=2025-07-07T14:36:21+0800 lvl=info msg="started tunnel" obj=tunnels name=command_line addr=//localhost:19001 url=tcp://0.tcp.jp.ngrok.io:17654 [service1] t=2025-07-07T14:36:21+0800 lvl=info msg="started tunnel" obj=tunnels name=command_line addr=//localhost:19000 url=tcp://0.tcp.jp.ngrok.io:14220 [service3] t=2025-07-07T14:36:21+0800 lvl=info msg="started tunnel" obj=tunnels name=command_line addr=//localhost:19002 url=tcp://0.tcp.jp.ngrok.io:13258
|