How to pipe the result of "ngrok http 8000" to another file?

Viewed 489

I use ngrok for testing webhooks, and I find myself constantly copy/pasting the newly generated ngrok host into several places, so I decided to automate this process, but can't seem to find a clean way to extract the url from the ngrok process.

I expected to be able to pipe the output to a file, then extract it using regex or something, but the stdout appears to be empty.

For example, the following command results in an empty file: ngrok http 8000 > test.txt

This is the output of ngrok http 8000:

output of ngrok http 8000

I managed to find a hack using python+selenium and ngrok's "inspect":

#!/usr/bin/env python3
from selenium import webdriver

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import WebDriverException

def main():
    opts = Options()
    opts.headless = True
    bot = webdriver.Firefox(options=opts)
    bot.get('http://localhost:4040/inspect/http')
    url_xpath = '/html/body/div[2]/div/div/div/div/ul/li[1]/a'
    WebDriverWait(bot, 10).until(EC.element_to_be_clickable((By.XPATH, url_xpath)))
    url = bot.find_element_by_xpath(url_xpath).text
    print(url.partition('://')[2])
    bot.close()


if __name__ == '__main__':
    main()

But this is slow, and a ton of code for something so trivial. Also, it doesn't account from ngrok randomly changing the inspect port.

Is there a better way to do this?

0 Answers
Related