在后台运行时查看随机ngrok URL

问题描述 投票:0回答:16

当我使用

./ngrok tcp 22
启动 ngrok 客户端时,它在前台运行,我可以看到随机生成的转发 URL,例如
tcp://0.tcp.ngrok.io:12345 -> localhost:22

如果我在后台运行

./ngrok tcp &
,我找不到任何方法来查看转发 URL。如何在后台运行 ngrok 并仍然看到 URL?

ngrok
16个回答
63
投票

有几种方法。

您可以:

1) 在浏览器中访问

localhost:4040/status
以查看一堆信息,或者

2)使用curl来打API:

localhost:4040/api/tunnels


25
投票

如果您想获得第一条隧道,那么

jq
将是您的朋友:

curl -s localhost:4040/api/tunnels | jq -r '.tunnels[0].public_url'

当运行多个 ngrok 实例时,请使用隧道名称

/api/tunnels/:name


19
投票

这个小 Python (2.7) 脚本将调用 ngrok API 并打印当前 URL:

import json
import os 

os.system("curl  http://localhost:4040/api/tunnels > tunnels.json")

with open('tunnels.json') as data_file:    
    datajson = json.load(data_file)


msg = "ngrok URL's: \n'
for i in datajson['tunnels']:
  msg = msg + i['public_url'] +'\n'

print (msg)

5
投票

运行 ./ngrok http & 这会将 ngrok 隧道作为后台进程运行。 Ngrok 通常会打开一个窗口,显示分配的 URL,但由于我们使用的是 nohup 命令,所以这是不可见的。

因此,然后运行

curl http://127.0.0.1:4040/api/tunnels
也可以看到ngrok分配的URL


4
投票

如果它对任何人有帮助,我编写了一个快速脚本来提取 Node 中生成的随机 url:

它假设您只对安全网址感兴趣。

const fetch = require('node-fetch')
fetch('http://localhost:4040/api/tunnels')
  .then(res => res.json())
  .then(json => json.tunnels.find(tunnel => tunnel.proto === 'https'))
  .then(secureTunnel => console.log(secureTunnel.public_url))
  .catch(err => {
    if (err.code === 'ECONNREFUSED') {
      return console.error("Looks like you're not running ngrok.")
    }
    console.error(err)
  })

如果您想要所有隧道:

const fetch = require('node-fetch')
fetch('http://localhost:4040/api/tunnels')
  .then(res => res.json())
  .then(json => json.tunnels.map(tunnel => tunnel.public_url))
  .then(publicUrls => publicUrls.forEach(url => console.log(url)))
  .catch(err => {
    if (err.code === 'ECONNREFUSED') {
      return console.error(
        "Looks like you're not running ngrok."
      )
    }
    console.error(err)
  })

4
投票

使用 ngrok API 获取所有活动 URL

您需要先生成一个令牌(https://dashboard.ngrok.com/api

然后从 API 获取活动端点

curl \
-H "Authorization: Bearer {API_KEY}" \
-H "Ngrok-Version: 2" \
https://api.ngrok.com/endpoints

检查文档:https://ngrok.com/docs/api/resources/endpoints


3
投票
import json
import requests


def get_ngrok_url():
    url = "http://localhost:4040/api/tunnels/"
    res = requests.get(url)
    res_unicode = res.content.decode("utf-8")
    res_json = json.loads(res_unicode)
    for i in res_json["tunnels"]:
        if i['name'] == 'command_line':
            return i['public_url']
            break

这是 JUN_NETWORKS python 3 代码的编辑。它仅输出 HTTPS URL。我发现 Ngrok 会随机改变 URL 先显示的顺序,有时会输出 HTTP。附加循环将始终寻找名为“command_line”的“隧道”,即 HTTPS URL。


3
投票

检查随机生成的 URL 的最简单方法是转到 ngrok 官方网站 > 仪表板 > 端点 > 状态 并检查我的端点的 URL 和状态

PS:当没有文档通过 API 获取这些端点时,创建了一条评论。我在这里描述了它


2
投票
在Python3中

import json import requests def get_ngrok_url(): url = "http://localhost:4040/api/tunnels" res = requests.get(url) res_unicode = res.content.decode("utf-8") res_json = json.loads(res_unicode) return res_json["tunnels"][0]["public_url"]

返回的 json 有 2 个 url 为

httphttps。 如果您只想要 https url,您 res_json["tunnels"][index num]["proto"]


    


2
投票
如果您喜欢 PowerShell,它就在变量中。

$ngrokOutput = ConvertFrom-Json (Invoke-WebRequest -Uri http://localhost:4040/api/tunnels).Content $httpsUrl = $ngrokOutput.tunnels.public_url[0] $httpUrl = $ngrokOutput.tunnels.public_url[1]
    

1
投票
红宝石

require 'httparty' # get ngrok public url begin response = HTTParty.get 'http://localhost:4040/api/tunnels' json = JSON.parse response.body new_sms_url = json['tunnels'].first['public_url'] rescue Errno::ECONNREFUSED print 'no ngrok instance found. shutting down' exit end
    

0
投票
Node.js 解决方案。

奖励:它将 url 复制到 Windows、Mac 和 Linux 中的剪贴板1

const http = require("http"); const { execSync } = require("child_process"); const callback = (res) => { let data = ""; res.on("data", (chunk) => (data += chunk)); res.on("end", () => { const resJSON = JSON.parse(data); const tunnels = resJSON.tunnels; const { public_url: url } = tunnels.find(({ proto }) => proto === "https"); console.log(url); // Copy to clipboard switch (process.platform) { case "win32": execSync(`echo ${url} | clip`); break; case "darwin": execSync(`echo ${url} | pbcopy`); break; case "linux": // NOTE: this requires xclip to be installed execSync(`echo ${url} | xclip -selection clipboard`); break; default: break; } }); }; http.get("http://localhost:4040/api/tunnels", callback);
[1]您需要先安装

xclip

sudo apt-get install xclip
    

0
投票
如果你使用的是nodejs,我就这么做了

const getURL = async () => { // inspect if the callback is working at: http://127.0.0.1:4040/inspect/http const ngrok = await import('ngrok') const api = ngrok.getApi(); const { tunnels } = JSON.parse(await api?.get('api/tunnels') ?? '{}') // if we already have a tunnel open, disconnect. We're only allowed to have 4 if (tunnels?.length > 0) await ngrok.disconnect() return await ngrok.connect(3000) }
    

0
投票
这是一个 C# 解决方案,它从

localhost:4040/api 提供的 ngrok Agent API

 获取第一个 URL。

//fetch xml from API `api/tunnels/command_line` using var httpClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:4040/api/tunnels/command_line"); request.Headers.Add(HttpRequestHeader.Accept.ToString(), "application/xml"); var response = await httpClient.SendAsync(request); var content = await response.Content.ReadAsStringAsync(); //parse and get the first PublicURL element's text const string Xpath = "/tunnelResource/PublicURL"; var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(content); var xmlNode = xmlDocument.SelectSingleNode(Xpath); var xmlElement = xmlNode as XmlElement; var url = xmlElement.InnerText;
    

-1
投票
可能我回答有点晚了,但如果这对访问该问题的人有帮助,我会很高兴。

***以上答案是查看/检查重定向 URL 的解决方案。但是,要在后台运行 ngrok,您可以尝试在 linux 中使用 screen 。如果您需要帮助,请快速

参考

步骤: 1.只需在屏幕中运行ngrok,然后分离。 2.使用上面Gerard给出的python脚本来查看URL。

我遵循了相同的过程并且有效!


-1
投票
有一个更好的方法,只需登录您在 ngrok.com 上的帐户即可。 您的 URL 将在您的仪表板中。

© www.soinside.com 2019 - 2024. All rights reserved.