예제 #1
0
    def test_multiple_processes_different_binaries(self):
        # GIVEN
        self.given_ngrok_installed(self.pyngrok_config)
        self.assertEqual(len(process._current_processes.keys()), 0)
        installer.install_default_config(self.pyngrok_config.config_path,
                                         {"web_addr": "localhost:4040"})

        ngrok_path2 = os.path.join(conf.BIN_DIR, "2",
                                   installer.get_ngrok_bin())
        pyngrok_config2 = PyngrokConfig(ngrok_path=ngrok_path2)
        self.given_ngrok_installed(pyngrok_config2)
        config_path2 = os.path.join(self.config_dir, "config2.yml")
        installer.install_default_config(config_path2,
                                         {"web_addr": "localhost:4041"})
        pyngrok_config2 = PyngrokConfig(ngrok_path=ngrok_path2,
                                        config_path=config_path2)

        # WHEN
        ngrok_process1 = process._start_process(self.pyngrok_config)
        ngrok_process2 = process._start_process(pyngrok_config2)

        # THEN
        self.assertEqual(len(process._current_processes.keys()), 2)
        self.assertIsNotNone(ngrok_process1)
        self.assertIsNone(ngrok_process1.proc.poll())
        self.assertTrue(ngrok_process1._monitor_thread.is_alive())
        self.assertTrue(urlparse(ngrok_process1.api_url).port, "4040")
        self.assertIsNotNone(ngrok_process2)
        self.assertIsNone(ngrok_process2.proc.poll())
        self.assertTrue(ngrok_process2._monitor_thread.is_alive())
        self.assertTrue(urlparse(ngrok_process2.api_url).port, "4041")
예제 #2
0
    def test_start_process_port_in_use(self):
        # GIVEN
        self.given_ngrok_installed(self.pyngrok_config.ngrok_path)
        self.assertEqual(len(process._current_processes.keys()), 0)
        ngrok_process = process._start_process(self.pyngrok_config)
        port = urlparse(ngrok_process.api_url).port
        self.assertEqual(len(process._current_processes.keys()), 1)
        self.assertTrue(ngrok_process._monitor_thread.is_alive())

        ngrok_path2 = os.path.join(conf.BIN_DIR, "2", installer.get_ngrok_bin())
        self.given_ngrok_installed(ngrok_path2)
        config_path2 = os.path.join(self.config_dir, "config2.yml")
        installer.install_default_config(config_path2, {"web_addr": ngrok_process.api_url.lstrip("http://")})
        pyngrok_config2 = PyngrokConfig(ngrok_path=ngrok_path2, config_path=config_path2)

        error = None
        retries = 0
        while error is None and retries < 10:
            time.sleep(1)

            # WHEN
            with self.assertRaises(PyngrokNgrokError) as cm:
                process._start_process(pyngrok_config2)

            error = cm.exception.ngrok_error
            retries += 1

        # THEN
        self.assertIsNotNone(error)
        if platform.system() == "Windows":
            self.assertIn("{}: bind: Only one usage of each socket address".format(port), cm.exception.ngrok_error)
        else:
            self.assertIn("{}: bind: address already in use".format(port), str(cm.exception.ngrok_error))
        self.assertEqual(len(process._current_processes.keys()), 1)
예제 #3
0
    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)
예제 #4
0
    def test_regional_subdomain(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)
        subdomain = "pyngrok-{}-{}-{}{}-http".format(
            platform.system(), platform.python_implementation(),
            sys.version_info[0], sys.version_info[1]).lower()
        pyngrok_config = PyngrokConfig(
            config_path=conf.DEFAULT_NGROK_CONFIG_PATH,
            auth_token=os.environ["NGROK_AUTHTOKEN"],
            region="au")

        # WHEN
        url = ngrok.connect(5000,
                            options={"subdomain": subdomain},
                            pyngrok_config=pyngrok_config)
        current_process = ngrok.get_ngrok_process()

        # THEN
        self.assertIsNotNone(current_process)
        self.assertIsNone(current_process.proc.poll())
        self.assertIsNotNone(url)
        self.assertIsNotNone(process.get_process(pyngrok_config))
        self.assertIn("http://", url)
        self.assertIn(".au.", url)
        self.assertIn(subdomain, url)
        self.assertEqual(len(process._current_processes.keys()), 1)
예제 #5
0
def disconnect(public_url, pyngrok_config=None):
    """
    Disconnect the :code:`ngrok` tunnel for the given URL.

    If :code:`ngrok` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s :code:`ngrok_path`, calling this method
    will first download and install :code:`ngrok`.

    If :code:`ngrok` is not running, calling this method will first start a process with
    :class:`~pyngrok.conf.PyngrokConfig`.

    :param public_url: The public URL of the tunnel to disconnect.
    :type public_url: str
    :param pyngrok_config: The :code:`pyngrok` configuration to use when interacting with the :code:`ngrok` binary.
    :type pyngrok_config: PyngrokConfig, optional
    """
    if pyngrok_config is None:
        pyngrok_config = PyngrokConfig()

    api_url = get_ngrok_process(pyngrok_config).api_url

    tunnels = get_tunnels(pyngrok_config)
    for tunnel in tunnels:
        if tunnel.public_url == public_url:
            logger.debug("Disconnecting tunnel: {}".format(tunnel.public_url))

            api_request("{}{}".format(api_url, tunnel.uri.replace("+", "%20")),
                        method="DELETE",
                        timeout=pyngrok_config.request_timeout)

            break
예제 #6
0
    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
        ngrok_tunnel = 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.assertTrue(ngrok_tunnel.name.startswith("http-file-"))
        self.assertEqual("file:///", ngrok_tunnel.config["addr"])
        self.assertIsNotNone(ngrok_tunnel.public_url)
        self.assertIsNotNone(process.get_process(self.pyngrok_config))
        self.assertIn('http://', ngrok_tunnel.public_url)
        self.assertEqual(len(process._current_processes.keys()), 1)
예제 #7
0
    def test_regional_tcp(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)
        subdomain = "pyngrok-{}-{}-{}{}-tcp".format(
            platform.system(), platform.python_implementation(),
            sys.version_info[0], sys.version_info[1]).lower()
        pyngrok_config = PyngrokConfig(
            config_path=conf.DEFAULT_NGROK_CONFIG_PATH,
            auth_token=os.environ["NGROK_AUTHTOKEN"],
            region="au")

        # WHEN
        ngrok_tunnel = ngrok.connect(5000,
                                     "tcp",
                                     subdomain=subdomain,
                                     pyngrok_config=pyngrok_config)
        current_process = ngrok.get_ngrok_process()

        # THEN
        self.assertIsNotNone(current_process)
        self.assertIsNone(current_process.proc.poll())
        self.assertIsNotNone(ngrok_tunnel.public_url)
        self.assertIsNotNone(process.get_process(pyngrok_config))
        self.assertEqual("localhost:5000", ngrok_tunnel.config["addr"])
        self.assertIn("tcp://", ngrok_tunnel.public_url)
        self.assertIn(".au.", ngrok_tunnel.public_url)
        self.assertEqual(len(process._current_processes.keys()), 1)
예제 #8
0
def get_tunnels(pyngrok_config=None):
    """
    Retrieve a list of active :code:`ngrok` tunnels for the given config's :code:`ngrok_path`.

    If :code:`ngrok` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s :code:`ngrok_path`, calling this method
    will first download and install :code:`ngrok`.

    If :code:`ngrok` is not running, calling this method will first start a process with
    :class:`~pyngrok.conf.PyngrokConfig`.

    :param pyngrok_config: The :code:`pyngrok` configuration to use when interacting with the :code:`ngrok` binary.
    :type pyngrok_config: PyngrokConfig, optional
    :return: The active :code:`ngrok` tunnels.
    :rtype: list[NgrokTunnel]
    """
    if pyngrok_config is None:
        pyngrok_config = PyngrokConfig()

    api_url = get_ngrok_process(pyngrok_config).api_url

    tunnels = []
    for tunnel in api_request(
            "{}/api/{}".format(api_url, "tunnels"),
            method="GET",
            data=None,
            timeout=pyngrok_config.request_timeout)["tunnels"]:
        tunnels.append(NgrokTunnel(tunnel))

    return tunnels
예제 #9
0
def connect(port="80",
            proto="http",
            name=None,
            options=None,
            pyngrok_config=None):
    """
    Establish a new :code:`ngrok` tunnel to the given port and protocol, returning the connected
    public URL that tunnels to the local port.

    If :code:`ngrok` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s :code:`ngrok_path`, calling this method
    will first download and install :code:`ngrok`.

    If :code:`ngrok` is not running, calling this method will first start a process with
    :class:`~pyngrok.conf.PyngrokConfig`.

    :param port: The local port to which the tunnel will forward traffic, defaults to "80". Can also be
        a `local directory or network address <https://ngrok.com/docs#http-file-urls>`_.
    :type port: str, optional
    :param proto: The protocol to tunnel, defaults to "http".
    :type proto: str, optional
    :param name: A friendly name for the tunnel.
    :type name: str, optional
    :param options: Parameters passed to `configuration for the ngrok
        tunnel <https://ngrok.com/docs#tunnel-definitions>`_.
    :type options: dict[str, str], optional
    :param pyngrok_config: The :code:`pyngrok` configuration to use when interacting with the :code:`ngrok` binary.
    :type pyngrok_config: PyngrokConfig, optional
    :return: The connected public URL.
    :rtype: str
    """
    if options is None:
        options = {}
    if pyngrok_config is None:
        pyngrok_config = PyngrokConfig()

    port = str(port)
    if not name:
        if not port.startswith("file://"):
            name = "{}-{}-{}".format(proto, port, uuid.uuid4())
        else:
            name = "{}-file-{}".format(proto, uuid.uuid4())

    config = {"name": name, "addr": port, "proto": proto}
    options.update(config)

    api_url = get_ngrok_process(pyngrok_config).api_url

    logger.debug("Connecting tunnel with options: {}".format(options))

    tunnel = NgrokTunnel(
        api_request("{}/api/{}".format(api_url, "tunnels"),
                    method="POST",
                    data=options,
                    timeout=pyngrok_config.request_timeout))

    if proto == "http" and ("bind_tls" not in options
                            or options["bind_tls"] is not False):
        tunnel.public_url = tunnel.public_url.replace("https", "http")

    return tunnel.public_url
예제 #10
0
    def test_tunnel_definitions_pyngrok_default_with_overrides(self):
        if "NGROK_AUTHTOKEN" not in os.environ:
            self.skipTest("NGROK_AUTHTOKEN environment variable not set")

        # GIVEN
        config = {
            "tunnels": {
                "pyngrok-default": {
                    "proto": "http",
                    "addr": "8080",
                    "subdomain": "pyngrok2"
                }
            }
        }
        config_path = os.path.join(self.config_dir, "config2.yml")
        installer.install_default_config(config_path, config)
        pyngrok_config = PyngrokConfig(config_path=config_path,
                                       auth_token=os.environ["NGROK_AUTHTOKEN"])

        # WHEN
        ngrok_tunnel1 = ngrok.connect(pyngrok_config=pyngrok_config)
        ngrok_tunnel2 = ngrok.connect(5000, subdomain="pyngrok3", pyngrok_config=pyngrok_config)

        # THEN
        self.assertEqual(ngrok_tunnel1.name, "pyngrok-default (http)")
        self.assertEqual(ngrok_tunnel1.config["addr"],
                         "http://localhost:{}".format(config["tunnels"]["pyngrok-default"]["addr"]))
        self.assertEqual(ngrok_tunnel1.proto, config["tunnels"]["pyngrok-default"]["proto"])
        self.assertEqual(ngrok_tunnel1.public_url,
                         "http://{}.ngrok.io".format(config["tunnels"]["pyngrok-default"]["subdomain"]))
        self.assertEqual(ngrok_tunnel2.name, "pyngrok-default (http)")
        self.assertEqual(ngrok_tunnel2.config["addr"], "http://localhost:5000")
        self.assertEqual(ngrok_tunnel2.proto, config["tunnels"]["pyngrok-default"]["proto"])
        self.assertEqual(ngrok_tunnel2.public_url, "http://pyngrok3.ngrok.io")
예제 #11
0
def ngrokServer():
    config = PyngrokConfig(
        region="au")  #Change region here if you would like to
    ngrok_url = ngrok.connect(80, 'http', pyngrok_config=config)
    print(
        style.GREEN('[+]') +
        style.RESET(f' Send this link to your victim: {ngrok_url} '))
예제 #12
0
    def setUp(self):
        self.config_dir = os.path.normpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), ".ngrok2"))
        config_path = os.path.join(self.config_dir, "config.yml")

        conf.DEFAULT_NGROK_CONFIG_PATH = config_path

        self.pyngrok_config = PyngrokConfig(config_path=conf.DEFAULT_NGROK_CONFIG_PATH)

        installer.DEFAULT_RETRY_COUNT = 1
예제 #13
0
 def prepare_tunnel(self):
     if self._tunnel is None:
         self._tunnel = cast(
             NgrokTunnel,
             ngrok.connect(
                 port=self.port,
                 proto="tcp",
                 pyngrok_config=PyngrokConfig(auth_token=self._auth_token),
                 return_ngrok_tunnel=True))
예제 #14
0
    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))
예제 #15
0
    def test_no_monitor_thread(self):
        # GIVEN
        self.given_ngrok_installed(self.pyngrok_config.ngrok_path)
        pyngrok_config = PyngrokConfig(config_path=conf.DEFAULT_NGROK_CONFIG_PATH, monitor_thread=False)

        # WHEN
        ngrok.connect(pyngrok_config=pyngrok_config)
        ngrok_process = ngrok.get_ngrok_process()

        # THEN
        self.assertIsNone(ngrok_process._monitor_thread)
예제 #16
0
    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 = PyngrokConfig(config_path=conf.DEFAULT_NGROK_CONFIG_PATH)
        conf.set_default(self.pyngrok_config)

        # ngrok's CDN can be flaky, so make sure its flakiness isn't reflect in our CI/CD test runs
        installer.DEFAULT_RETRY_COUNT = 3
예제 #17
0
def kill(pyngrok_config=None):
    """
    Terminate the :code:`ngrok` processes, if running, for the given config's :code:`ngrok_path`. This method will not
    block, it will just issue a kill request.

    :param pyngrok_config: The :code:`pyngrok` configuration to use when interacting with the :code:`ngrok` binary.
    :type pyngrok_config: PyngrokConfig, optional
    """
    if pyngrok_config is None:
        pyngrok_config = PyngrokConfig()

    process.kill_process(pyngrok_config.ngrok_path)
예제 #18
0
    def test_log_event_callback_and_max_logs(self):
        # GIVEN
        self.given_ngrok_installed(self.pyngrok_config.ngrok_path)
        log_event_callback_mock = mock.MagicMock()
        pyngrok_config = PyngrokConfig(config_path=conf.DEFAULT_NGROK_CONFIG_PATH,
                                       log_event_callback=log_event_callback_mock, max_logs=5)

        # WHEN
        ngrok.connect(pyngrok_config=pyngrok_config)
        ngrok_process = ngrok.get_ngrok_process()
        time.sleep(1)

        # THEN
        self.assertGreater(log_event_callback_mock.call_count, len(ngrok_process.logs))
        self.assertEqual(len(ngrok_process.logs), 5)
예제 #19
0
    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 = PyngrokConfig(config_path=conf.DEFAULT_NGROK_CONFIG_PATH,
                                            # When running parallel CI/CD tests against the same ngrok account, ngrok
                                            # can start rejecting connections, which is easily mitigated with retries
                                            # to ensure test stability
                                            reconnect_session_retries=10)
        conf.set_default(self.pyngrok_config)

        # ngrok's CDN can be flaky, so make sure its flakiness isn't reflect in our CI/CD test runs
        installer.DEFAULT_RETRY_COUNT = 3
예제 #20
0
    def test_tunnel_definitions(self):
        if "NGROK_AUTHTOKEN" not in os.environ:
            self.skipTest("NGROK_AUTHTOKEN environment variable not set")

        # GIVEN
        config = {
            "tunnels": {
                "http-tunnel": {
                    "proto": "http",
                    "addr": "8000",
                    "subdomain": "pyngrok1"
                },
                "tcp-tunnel": {
                    "proto": "tcp",
                    "addr": "22"
                }
            }
        }
        config_path = os.path.join(self.config_dir, "config2.yml")
        installer.install_default_config(config_path, config)
        pyngrok_config = PyngrokConfig(
            config_path=config_path, auth_token=os.environ["NGROK_AUTHTOKEN"])

        # WHEN
        http_tunnel = ngrok.connect(name="http-tunnel",
                                    pyngrok_config=pyngrok_config)
        ssh_tunnel = ngrok.connect(name="tcp-tunnel",
                                   pyngrok_config=pyngrok_config)

        # THEN
        self.assertEqual(http_tunnel.name, "http-tunnel (http)")
        self.assertEqual(
            http_tunnel.config["addr"], "http://localhost:{}".format(
                config["tunnels"]["http-tunnel"]["addr"]))
        self.assertEqual(http_tunnel.proto,
                         config["tunnels"]["http-tunnel"]["proto"])
        self.assertEqual(
            http_tunnel.public_url, "http://{}.ngrok.io".format(
                config["tunnels"]["http-tunnel"]["subdomain"]))
        self.assertEqual(ssh_tunnel.name, "tcp-tunnel")
        self.assertEqual(
            ssh_tunnel.config["addr"],
            "localhost:{}".format(config["tunnels"]["tcp-tunnel"]["addr"]))
        self.assertEqual(ssh_tunnel.proto,
                         config["tunnels"]["tcp-tunnel"]["proto"])
        self.assertTrue(ssh_tunnel.public_url.startswith("tcp://"))
예제 #21
0
    def test_get_tunnel_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"])
        ngrok_tunnel = ngrok.connect("file:///", pyngrok_config=pyngrok_config)
        time.sleep(1)
        api_url = ngrok.get_ngrok_process(pyngrok_config).api_url

        # WHEN
        response = ngrok.api_request("{}{}".format(api_url, ngrok_tunnel.uri), "GET")

        # THEN
        self.assertEqual(ngrok_tunnel.name, response["name"])
        self.assertTrue(ngrok_tunnel.name.startswith("http-file-"))
예제 #22
0
def set_auth_token(token, pyngrok_config=None):
    """
    Set the :code:`ngrok` auth token in the config file, enabling authenticated features (for instance,
    more concurrent tunnels, custom subdomains, etc.).

    If :code:`ngrok` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s :code:`ngrok_path`, calling this method
    will first download and install :code:`ngrok`.

    :param token: The auth token to set.
    :type token: str
    :param pyngrok_config: The :code:`pyngrok` configuration to use when interacting with the :code:`ngrok` binary.
    :type pyngrok_config: PyngrokConfig, optional
    """
    if pyngrok_config is None:
        pyngrok_config = PyngrokConfig()

    ensure_ngrok_installed(pyngrok_config.ngrok_path)

    process.set_auth_token(pyngrok_config, token)
예제 #23
0
    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).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)
예제 #24
0
    def test_start_new_session(self, mock_popen):
        # GIVEN
        self.given_ngrok_installed(self.pyngrok_config.ngrok_path)

        # WHEN
        pyngrok_config = PyngrokConfig(
            config_path=conf.DEFAULT_NGROK_CONFIG_PATH, start_new_session=True)
        try:
            process._start_process(pyngrok_config=pyngrok_config)
        except TypeError:
            # Since we're mocking subprocess.Popen, this call will ultimately fail, but it gets far enough for us to
            # validate our assertion
            pass

        # THEN
        mock_popen.assert_called()
        if sys.version_info.major >= 3 and os.name == "posix":
            self.assertIn("start_new_session", mock_popen.call_args[1])
        else:
            self.assertNotIn("start_new_session", mock_popen.call_args[1])
예제 #25
0
def get_ngrok_process(pyngrok_config=None):
    """
    Retrieve the current :code:`ngrok` process for the given config's :code:`ngrok_path`.

    If :code:`ngrok` is not installed at :class:`~pyngrok.conf.PyngrokConfig`'s :code:`ngrok_path`, calling this method
    will first download and install :code:`ngrok`.

    If :code:`ngrok` is not running, calling this method will first start a process with
    :class:`~pyngrok.conf.PyngrokConfig`.

    :param pyngrok_config: The :code:`pyngrok` configuration to use when interacting with the :code:`ngrok` binary.
    :type pyngrok_config: PyngrokConfig, optional
    :return: The :code:`ngrok` process.
    :rtype: NgrokProcess
    """
    if pyngrok_config is None:
        pyngrok_config = PyngrokConfig()

    ensure_ngrok_installed(pyngrok_config.ngrok_path)

    return process.get_process(pyngrok_config)
예제 #26
0
    print("Request body: " + body)
    # handle webhook body and signature
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        print(
            "Invalid signature. Please check your channel access token/channel secret."
        )
        abort(400)
    except Exception as err:
        print(err)
    return "OK"


NGROK_TOKEN = os.environ["NGROK_TOKEN"]
pyngrok_config = PyngrokConfig(region="jp")
ngrok.set_auth_token(NGROK_TOKEN)


@handler.add(BeaconEvent)
def handle_beacon_event(event):
    global notify
    if isinstance(event.source, SourceUser):
        profile = line_bot_api.get_profile(event.source.user_id)
        # encode_str = hashlib.md5(event.source.user_id.encode())
        if event.beacon.type == "enter":
            line_bot_api.push_message(
                event.source.user_id,
                [
                    TextSendMessage(text=profile.display_name +
                                    " Entered beacon's reception range"),
예제 #27
0
    def _ngrok_connect(self):
        if self._retry_connect_timer:
            self._retry_connect_timer = None

        if self._ngrok_started:
            self._ngrok_disconnect()

        if not self._settings.get(["token"]):
            self._logger.warning("Ngrok auth token is not configured")
            self._plugin_manager.send_plugin_message(
                self._identifier,
                dict(
                    error=
                    "The auth token is not configured. An auth token is required to create a secure tunnel."
                ))

            self._restart_ngrok = True
            self._attempting_connect_on_start = False

            return

        if not (self._settings.get(["auth_name"])
                and self._settings.get(["auth_pass"])):
            self._logger.warning("Basic Auth is not configured")
            self._plugin_manager.send_plugin_message(
                self._identifier,
                dict(
                    error=
                    "The username and password are not configured. Authentication is required to create a secure tunnel."
                ))
            self._attempting_connect_on_start = False

            return

        pyngrok_config = PyngrokConfig()
        pyngrok_config.log_event_callback = self.on_ngrok_log_event
        pyngrok_config.auth_token = self._settings.get(["token"])
        pyngrok_config.region = self._settings.get(["region"])

        if self._restart_ngrok:
            self._logger.info("Setting ngrok auth token & region...")
            if self._ngrok_started:
                ngrok.kill()  # Make sure no previous token is used

            # Resettimg the _restart_ngrok flag is postponed until we know the restart was succesful
            # because otherwise the token and region may not "take".

        self._logger.info("Opening ngrok tunnel...")
        options = dict(bind_tls=True,
                       inspect=False,
                       auth="%s:%s" % (self._settings.get(
                           ["auth_name"]), self._settings.get(["auth_pass"])))

        if self._settings.get(["subdomain"]):
            options["subdomain"] = self._settings.get(["subdomain"])
        if self._settings.get(["hostname"]):
            options["hostname"] = self._settings.get(["hostname"])

        try:
            if self._legacy_ngrok:
                tunnel = ngrok.connect(
                    port=self._settings.get_int(["port"]),
                    options=options,
                    pyngrok_config=pyngrok_config)  # type:str
            else:
                tunnel = ngrok.connect(addr=self._settings.get_int(["port"]),
                                       pyngrok_config=pyngrok_config,
                                       **options)  # type:NgrokTunnel
            self._ngrok_started = True
        except PyngrokNgrokError:
            self._logger.error("Could not connect with the provided API key")
            self._attempting_connect_on_start = False
            return

        self._attempting_connect_on_start = False
        if tunnel:
            if self._legacy_ngrok:
                tunnel_url = tunnel
            else:
                tunnel_url = tunnel.public_url
            self._tunnel_url = tunnel_url.partition("://")[2]
            self._logger.info("ngrok tunnel: %s" % self._tunnel_url)
            self._plugin_manager.send_plugin_message(
                self._identifier, dict(tunnel=self._tunnel_url))

            self._event_bus.fire(Events.PLUGIN_NGROK_CONNECTED,
                                 dict(tunnel=self._tunnel_url))

            self._restart_ngrok = False
예제 #28
0
from pyngrok import ngrok
from pyngrok.conf import PyngrokConfig

pyngrok_config = PyngrokConfig(
    auth_token="1hssImxw1hr36FoOzFmxuvC5VSu_3mqFmYhbjjfyqi5pCB4NV")
ngrok.connect(8080, pyngrok_config=pyngrok_config)
# ngrok.set_auth_token("1hssImxw1hr36FoOzFmxuvC5VSu_3mqFmYhbjjfyqi5pCB4NV")
tunnels = ngrok.get_tunnels()
public_url = tunnels[0].public_url
print(public_url)
예제 #29
0
cache = Cache(config={'CACHE_TYPE': 'simple'})
app = Flask(__name__)
ask = Ask(app, '/')
app.config.from_mapping(config)
if WINDOWS:
    app.config["CACHE_TYPE"] = "null"

app.config['INTEGRATIONS'] = ['ACTIONS_ON_GOOGLE']
cache.init_app(app)

port = 5000

if not WINDOWS:
    # Open a ngrok tunnel to the dev server
    print('setting up ngrok')
    pyngrok_config = PyngrokConfig(config_path='/home/pi/.ngrok2/ngrok.yml',
                                   region='eu')
    public_url = ngrok.connect(port,
                               options={"subdomain": 'woods'},
                               pyngrok_config=pyngrok_config)
    print(' * ngrok tunnel {public_url} -> http://127.0.0.1:' + str(port))

    # Update any base URLs or webhooks to use the public ngrok URL
    app.config["BASE_URL"] = public_url

    app.config['INTEGRATIONS'] = ['ACTIONS_ON_GOOGLE']

    vs = VideoStream(src=0).start()
    time.sleep(1.0)


@app.route("/image")