【问题标题】:View random ngrok URL when run in background在后台运行时查看随机 ngrok URL
【发布时间】:2016-03-23 05:40:47
【问题描述】:

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

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

【问题讨论】:

    标签: ngrok


    【解决方案1】:

    有几种方法。

    您可以:

    1) 在浏览器中访问localhost:4040/status 以查看大量信息,或

    2) 使用 curl 访问 API:localhost:4040/api/tunnels

    【讨论】:

      【解决方案2】:

      这个 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)
      

      【讨论】:

      • 只有 urllib.urlopen 的 python3 怎么办?我不想 1. 调用外部命令 curl,2. 重定向到文件..谢谢
      • 为什么要使用 curl(取决于系统)并将其保存在 json 文件中,而您只能发出 http 请求?
      【解决方案3】:

      如果您想获得第一条隧道,那么jq 将成为您的朋友:

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

      当运行多个 ngrok 实例时,请使用隧道名称 /api/tunnels/:name。

      【讨论】:

      • 由于某种原因,在 zsh 中,我不得不在 '[' 和 ']' 前加上 '\',所以这里我必须运行 curl -s localhost:4040/api/tunnels | jq -r .tunnels\[0\].public_url。但效果很好,谢谢!
      • @HenriqueBruno 为了便于携带,您可以使用双引号:curl -s localhost:4040/api/tunnels | jq -r ".tunnels[0].public_url"
      • 真的!还没想过。谢谢!
      • @François Leblanc 谢谢!
      【解决方案4】:

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

      假设您只对安全 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)
        })
      

      【讨论】:

        【解决方案5】:
        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。

        【讨论】:

          【解决方案6】:

          在 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 个用于 http 和 https 的 url。 如果你只想要https url,你res_json["tunnels"][index num]["proto"]

          【讨论】:

            【解决方案7】:

            如果你喜欢 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]
            

            【讨论】:

              【解决方案8】:

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

              因此,然后运行 ​​curl http://127.0.0.1:4040/api/tunnels 也可以看到 ngrok 分配的 URL

              【讨论】:

                【解决方案9】:

                我检查随机生成的 URL 的最简单方法是转到 ngrok official site > dashboard > endpoints > status 并检查我的端点的 URL 和状态

                【讨论】:

                • 这样 URL 不能用于程序和脚本。如果某些程序需要访问 ngrok URL,或者您需要使用正确的链接自动更新网页怎么办?
                【解决方案10】:

                在红宝石中

                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
                

                【讨论】:

                  【解决方案11】:

                  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
                  

                  【讨论】:

                    【解决方案12】:

                    如果您使用的是 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)
                    }
                    

                    【讨论】:

                    • 使用 const 隧道 = await api.listTunnels();而不是 api.get 作为其已弃用
                    【解决方案13】:

                    可能我回答得有点晚了,但如果它对任何访问该问题的人有帮助,我会很高兴。

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

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

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

                    【讨论】:

                      【解决方案14】:

                      有一种更好的方法,只需在 ngrok.com 上登录您的帐户即可。 您的网址将在您的仪表板中。

                      【讨论】:

                        猜你喜欢
                        • 2021-10-26
                        • 2020-10-19
                        • 1970-01-01
                        • 2022-01-17
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2014-02-19
                        相关资源
                        最近更新 更多