当我使用
./ngrok tcp 22
启动 ngrok 客户端时,它在前台运行,我可以看到随机生成的转发 URL,例如 tcp://0.tcp.ngrok.io:12345 -> localhost:22
。
如果我在后台运行
./ngrok tcp &
,我找不到任何方法来查看转发 URL。如何在后台运行 ngrok 并仍然看到 URL?
有几种方法。
您可以:
1) 在浏览器中访问
localhost:4040/status
以查看一堆信息,或者
2)使用curl来打API:
localhost:4040/api/tunnels
如果您想获得第一条隧道,那么
jq
将是您的朋友:
curl -s localhost:4040/api/tunnels | jq -r '.tunnels[0].public_url'
当运行多个 ngrok 实例时,请使用隧道名称
/api/tunnels/:name
。
这个小 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)
运行 ./ngrok http & 这会将 ngrok 隧道作为后台进程运行。 Ngrok 通常会打开一个窗口,显示分配的 URL,但由于我们使用的是 nohup 命令,所以这是不可见的。
因此,然后运行
curl http://127.0.0.1:4040/api/tunnels
也可以看到ngrok分配的URL
如果它对任何人有帮助,我编写了一个快速脚本来提取 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)
})
使用 ngrok API 获取所有活动 URL
您需要先生成一个令牌(https://dashboard.ngrok.com/api)
然后从 API 获取活动端点
curl \
-H "Authorization: Bearer {API_KEY}" \
-H "Ngrok-Version: 2" \
https://api.ngrok.com/endpoints
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。
检查随机生成的 URL 的最简单方法是转到 ngrok 官方网站 > 仪表板 > 端点 > 状态 并检查我的端点的 URL 和状态
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 为
http 和 https。
如果您只想要 https url,您 res_json["tunnels"][index num]["proto"]
$ngrokOutput = ConvertFrom-Json (Invoke-WebRequest -Uri http://localhost:4040/api/tunnels).Content
$httpsUrl = $ngrokOutput.tunnels.public_url[0]
$httpUrl = $ngrokOutput.tunnels.public_url[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
奖励:它将 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
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)
}
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;