When I start an ngrok client with ./ngrok tcp 22
it runs in the foreground and I can see the randoming generated forwarding URL, such as tcp://0.tcp.ngrok.io:
If it helps anyone I wrote a quick script to extract the generated random url in Node:
It makes assumption you're only interested in the secure 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)
})
If you wanted all tunnels:
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)
})
This little Python (2.7) script will call the ngrok API and print the current URL's:
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)
In 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"]
This returned json have 2 url for http and https.
If you want only https url, you res_json["tunnels"][index num]["proto"]
There is a better way to do that just login to your account on ngrok.com. Your URL will be in your dashboard.
If you want to get the first tunnel then jq
will be your friend:
curl -s localhost:4040/api/tunnels | jq -r .tunnels[0].public_url
When running more than one instance of ngrok then use the tunnel name /api/tunnels/:name
.
In Ruby
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