def run(host, port): print(f"Listening on {host}:{port}") server = HTTPServer((host, port), RequestHandler) print("Creating public urls:") http_public_url = ngrok.connect(port=port, proto="http", options={"bind_tls": "both"}) https_public_url = http_public_url.replace("http://", "https://") # fmt: off print( dedent(f""" The server is now accesible on: {http_public_url} {https_public_url} """)) # fmt: on try: server.serve_forever() except KeyboardInterrupt: print(f"Exiting") print("Shutting down public urls") ngrok.kill() ngrok.disconnect(http_public_url) ngrok.disconnect(https_public_url) time.sleep(2) print("Shutting down server") server.shutdown()
def _start_server(self): active_tunnels = ngrok.get_tunnels() for tunnel in active_tunnels: public_url = tunnel.public_url ngrok.disconnect(public_url) url = ngrok.connect(port=self.port, options={"bind_tls": True}) print(f"Code Server can be accessed on: {url}")
def end_ngrok(ngrok_url=None): logging.info("disconnecting ngrok") if ngrok_url: ngrok.disconnect(ngrok_url) ngrok.kill() sleep(5)
def test_connect_fileserver(self): if "NGROK_AUTHTOKEN" not in os.environ: self.skipTest("NGROK_AUTHTOKEN environment variable not set") # GIVEN self.assertEqual(len(process._current_processes.keys()), 0) pyngrok_config = PyngrokConfig( config_path=conf.DEFAULT_NGROK_CONFIG_PATH, auth_token=os.environ["NGROK_AUTHTOKEN"]) # WHEN url = ngrok.connect("file:///", pyngrok_config=pyngrok_config) current_process = ngrok.get_ngrok_process() time.sleep(1) tunnels = ngrok.get_tunnels() # THEN self.assertEqual(len(tunnels), 2) self.assertIsNotNone(current_process) self.assertIsNone(current_process.proc.poll()) self.assertTrue(current_process._monitor_thread.is_alive()) self.assertIsNotNone(url) self.assertIsNotNone(process.get_process(self.pyngrok_config)) self.assertIn('http://', url) self.assertEqual(len(process._current_processes.keys()), 1) # WHEN ngrok.disconnect(url) time.sleep(1) tunnels = ngrok.get_tunnels() # THEN # There is still one tunnel left, as we only disconnected the http tunnel self.assertEqual(len(tunnels), 1)
def ngrokDisconnect(update: Update, context: CallbackContext) -> None: if not checkId(update.message.chat_id): return update.message.reply_text("There are " + str(len(ngrok.get_tunnels())) + " open tunnel(s)") ngrok.disconnect(tunnel.public_url) update.message.reply_text( str(len(ngrok.get_tunnels())) + " tunnel(s) left open")
def stop_tunnel(self): """ Kill the current running ngrok tunnels """ if self.tunnel is None: return for tunnel in ngrok.get_tunnels(): ngrok.disconnect(tunnel.public_url) self.tunnel = None
def _start_server(self): active_tunnels = ngrok.get_tunnels() for tunnel in active_tunnels: public_url = tunnel.public_url ngrok.disconnect(public_url) url = ngrok.connect(addr=self.port, options={"bind_tls": True}, return_ngrok_tunnel=True) print(f'Web App can be accessed on: {url.public_url}')
def get_public_url(): previous_urls = ngrok.get_tunnels() for i in previous_urls: ngrok.disconnect(i.public_url) url = ngrok.connect(port=5000) url = url.replace('http', 'https') return url
def establish_tunnel(self): try: publicurl = ngrok.connect(port=self.port) print(f"The url is : {publicurl}") self.sw.serve() except KeyboardInterrupt: print("Killin tunnels ...") ngrok.disconnect(publicurl)
def _start_ngrok_server(self): if self.authtoken: ngrok.set_auth_token(self.authtoken) active_tunnels = ngrok.get_tunnels() for tunnel in active_tunnels: public_url = tunnel.public_url ngrok.disconnect(public_url) url = ngrok.connect(addr=self.port, options={"bind_tls": True}) return url
def _start_server(self): if self.authtoken: ngrok.set_auth_token(self.authtoken) active_tunnels = ngrok.get_tunnels() for tunnel in active_tunnels: public_url = tunnel.public_url ngrok.disconnect(public_url) url = ngrok.connect(addr=self.port, options={"bind_tls": True}) print(f"Code Server can be accessed on: {url}") self.url = url
def disconnect_tunnel(): tunnels = ngrok.get_tunnels() public_url = (tunnels.split( "NgrokTunnel: ", maxsplit=1)[-1].split(maxsplit=1)[0].strip('"')) ngrok.disconnect(public_url) ngrok.kill() tunnels_check = ngrok.get_tunnels() message = ("\nInitial tunnels: " + str(tunnels) + "\nFinal tunnels: " + str(tunnels_check)) return message
def stopNgrok(ngrokServiceUrl): try: from pyngrok import ngrok global __ngrok_ip__ ngrok.disconnect(ngrokServiceUrl) __services__.remove(ngrokServiceUrl) return True except Exception as e: Logger.printMessage(message='Couldn\'t stop ngrok service', description=str(e), is_error=True) return False
def disconnect(self): if self.option == "localtunnel": try: self.connection.kill() except: pass elif self.option == "ngrok": active_tunnels = ngrok.get_tunnels() for tunnel in active_tunnels: public_url = tunnel.public_url ngrok.disconnect(public_url)
def _start_server(self): if self.authtoken: ngrok.set_auth_token(self.authtoken) active_tunnels = ngrok.get_tunnels() for tunnel in active_tunnels: public_url = tunnel.public_url ngrok.disconnect(public_url) NgrokTunnel = ngrok.connect(addr=self.port, options={"bind_tls": True}) https_url = self._get_https_url(str(NgrokTunnel)) print(f'\n\nopen code server via https: {https_url}\n\n') print(f"Code Server can be accessed on: {NgrokTunnel}")
def _start_server(self): if self.authtoken: ngrok.set_auth_token(self.authtoken) active_tunnels = ngrok.get_tunnels() for tunnel in active_tunnels: public_url = tunnel.public_url ngrok.disconnect(public_url) url = ngrok.connect(addr=self.port, bind_tls=True) if self._code: print(f"Code Server can be accessed on: {url}") else: print(f"Public URL: {url}")
def close_tunnel(self, tunnel: str): """ Close an ``ngrok`` tunnel. :param tunnel: Name or public URL of the tunnel to be closed. """ from pyngrok import ngrok if tunnel in self._active_tunnels_by_name: tunnel = self._active_tunnels_by_name[tunnel]['url'] assert tunnel in self._active_tunnels_by_url, f'No such tunnel URL or name: {tunnel}' ngrok.disconnect(tunnel)
def _start_server(self): conf.get_default().region = self.region if self.authtoken: ngrok.set_auth_token(self.authtoken) active_tunnels = ngrok.get_tunnels() for tunnel in active_tunnels: public_url = tunnel.public_url ngrok.disconnect(public_url) url = ngrok.connect(addr=self.port, options={"bind_tls": True}) if self._code: print(f"Code Server can be accessed on: {url}") else: print(f"Public URL: {url}")
def delete_tunnels(self): try: for tunnel in ngrok.get_tunnels(): ngrok.disconnect(tunnel.public_url) if not ngrok.get_tunnels(): return 'All active Ngrok tunnels delete successfully!' return 'Something went wrong deleting the Ngrok tunnels!' except Exception as e: logger.exception(e) return self.error.format(e)
def close_the_app(self): self.reply = QMessageBox.information(self, "User Interface", "Are you sure you want to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if self.reply == QMessageBox.Yes: if self.is_save: self.write() ngrok.disconnect(self.public_url) self.serverThread.stop() self.Qrcode_msg.close() self.close()
async def manage_webhooks(self): refresh_webhooks = True while True: refreshed_ngrok = False if settings.USE_NGROK and self.ngrok_tunnel is None: self.public_url, self.ngrok_tunnel = await database_sync_to_async( setup_ngrok)() refreshed_ngrok = True elif settings.USE_NGROK: # Check to see if tunnel is still alive r = requests.get(f'{self.public_url}/api/v1/heartbeat') if r.status_code != 200: try: ngrok.disconnect(self.ngrok_tunnel.public_url) except: pass self.public_url, self.ngrok_tunnel = await database_sync_to_async( setup_ngrok)() refreshed_ngrok = True else: self.public_url = settings.BASE_URL await database_sync_to_async(self.set_setting )('PUBLIC_URL', settings.BASE_URL) # check for difference in required webhooks: new_event_sub_ids = await database_sync_to_async( get_active_event_sub_ids)() scopes_refreshed = await database_sync_to_async( self.lookup_setting)('SCOPES_REFRESHED') if set(self.active_event_sub_ids) != set( new_event_sub_ids) and scopes_refreshed: refresh_webhooks = True await database_sync_to_async(self.set_setting )('SCOPES_REFRESHED', False) if refresh_webhooks or refreshed_ngrok: await database_sync_to_async(self.setup_webhooks)() refresh_webhooks = False force_refresh_webhooks = await database_sync_to_async( self.lookup_setting)('FORCE_WEBHOOK_REFRESH') if force_refresh_webhooks: await database_sync_to_async(self.setup_webhooks)() await database_sync_to_async(self.set_setting )('FORCE_WEBHOOK_REFRESH', False) await asyncio.sleep(self.wh_delay)
def test_disconnect(self): # GIVEN url = ngrok.connect(pyngrok_config=self.pyngrok_config) time.sleep(1) tunnels = ngrok.get_tunnels() # Two tunnels, as one each was created for "http" and "https" self.assertEqual(len(tunnels), 2) # WHEN ngrok.disconnect(url) time.sleep(1) tunnels = ngrok.get_tunnels() # THEN # There is still one tunnel left, as we only disconnected the http tunnel self.assertEqual(len(tunnels), 1)
def connect_to_ngrok(port, authtoken=None): time.sleep(1) try: active_tunnels = ngrok.get_tunnels() time.sleep(1) for tunnel in active_tunnels: public_url = tunnel.public_url print(f"Disconnecting {public_url}") ngrok.disconnect(public_url) time.sleep(1) except: print("Some error in ngrok.get_tunnels()") # url = ngrok.connect(addr=port, options={"bind_tls":True}) if authtoken: ngrok.set_auth_token(authtoken) url = ngrok.connect(addr=port, bind_tls=True) time.sleep(1) print(f"Remote server can be assesed on : {url}") return url
def start_a_tunnel(port=8080): """ This function will start a tunnel in port given port, default is 8080 By default ngrok opens two tunnels 1. http 2. https I don't need http bind_tls=True tells ngrok to open only https tunnel """ # first I will check if there is any tunnel active # if there is any active tunnel we will disconnect it for each_tunnel in ngrok.get_tunnels(): print('Shutting down: ' + each_tunnel.public_url) ngrok.disconnect(each_tunnel.public_url) # now that it is made sure that there is no tunnels # we can open a new_tunnel tunnel = ngrok.connect(addr=port, proto='http', bind_tls=True) return tunnel.public_url
def _start_server(self): if self.authtoken: ngrok.set_auth_token(self.authtoken) active_tunnels = ngrok.get_tunnels() for tunnel in active_tunnels: used_port = int(tunnel.data['config']['addr'].rsplit(":")[-1]) public_url = tunnel.public_url if used_port == self.port: self.log("port already used {} -> localhost:{}".format( public_url, used_port), level="warn") self.log("disonnecting {}".format(public_url)) ngrok.disconnect(public_url) url = ngrok.connect(addr=self.port, options={"bind_tls": True}) url = str(url.public_url).replace("http", "https") self.log("code-server url {}".format(url))
def test_disconnect_fileserver(self): if "NGROK_AUTHTOKEN" not in os.environ: self.skipTest("NGROK_AUTHTOKEN environment variable not set") # GIVEN self.assertEqual(len(process._current_processes.keys()), 0) pyngrok_config = self.copy_with_updates(self.pyngrok_config, auth_token=os.environ["NGROK_AUTHTOKEN"]) url = ngrok.connect("file:///", pyngrok_config=pyngrok_config).public_url time.sleep(1) # WHEN ngrok.disconnect(url) time.sleep(1) tunnels = ngrok.get_tunnels() # THEN # There is still one tunnel left, as we only disconnected the http tunnel self.assertEqual(len(tunnels), 1)
def _ngrok_disconnect(self): self._logger.info("Closing any open ngrok tunnels") pyngrok_config = PyngrokConfig() pyngrok_config.auth_token = self._settings.get(["token"]) pyngrok_config.region = self._settings.get(["region"]) try: for tunnel in ngrok.get_tunnels(): self._logger.info("Closing tunnel %s" % tunnel.public_url) ngrok.disconnect(tunnel.public_url, pyngrok_config=pyngrok_config) except PyngrokNgrokError: pass self._event_bus.fire(Events.PLUGIN_NGROK_CLOSED, dict(tunnel=self._tunnel_url)) self._tunnel_url = "" self._plugin_manager.send_plugin_message(self._identifier, dict(tunnel=self._tunnel_url))
def runServer(): print(bc.BC + " Starting Ngrok HTTP Tunnel...") try: http_tunnel = ngrok.connect() time.sleep(1) if http_tunnel: serverStatus = sBan + ' Ngrok Tunnel: ' + bc.GC + 'Connected' else: serverStatus = eBan + ' Ngrok Tunnel: ' + bc.RC + 'Disconnected' os.system('clear') print(banner) print(serverStatus) brutoNovaURL = str(http_tunnel).replace('"', '').replace( 'NgrokTunnel: ', '').replace(' -> http://localhost:80', '').replace( 'http', 'https') + "/BrutoNova-UI/" time.sleep(0.5) print(bc.BC + ' Interface URL: ' + bc.GC + brutoNovaURL) ngrok_process = ngrok.get_ngrok_process() print(bc.BC + "\n" + iBan + bc.GC + " CTRL + C" + bc.BC + " to stop the server\n") os.chdir('/var/www/html/') subprocess.call(['php', '-S', 'localhost:80']) ngrok_process.proc.wait() except KeyboardInterrupt: os.system('clear') print(banner) print(bc.BC + " Closing PHP Web Server...") time.sleep(0.5) print(bc.BC + " Closing Ngrok HTTP Tunnel...") ngrok.disconnect(http_tunnel.public_url) time.sleep(0.5) print(bc.BC + " Killing Ngrok process...") time.sleep(0.5) ngrok.kill() time.sleep(0.5) os.system('clear') print(banner) quit()
def test_disconnect_fileserver(self): if "NGROK_AUTHTOKEN" not in os.environ: self.skipTest("NGROK_AUTHTOKEN environment variable not set") # GIVEN self.assertEqual(len(process._current_processes.keys()), 0) pyngrok_config = PyngrokConfig( config_path=conf.DEFAULT_NGROK_CONFIG_PATH, auth_token=os.environ["NGROK_AUTHTOKEN"]) url = ngrok.connect("file:///", pyngrok_config=pyngrok_config) time.sleep(1) tunnel = ngrok.get_tunnels()[0] api_url = ngrok.get_ngrok_process(pyngrok_config).api_url # WHEN ngrok.disconnect(url) time.sleep(1) tunnels = ngrok.get_tunnels() # THEN # There is still one tunnel left, as we only disconnected the http tunnel self.assertEqual(len(tunnels), 1)
def _shutdown(self): self.dtw.stop() ngrok.disconnect(self.callback_url)