Ejemplo n.º 1
0
    def _open_tunnels(self):
        self.tunnels = {}

        auth = {
            "ssh_username": self.user,
            "ssh_password": self.password,
            "ssh_pkey": self.pkey
        }

        if self.gateway:
            self.tunnels["gateway"] = open_tunnel(
                ssh_address_or_host=self.gateway,
                remote_bind_address=self.host,
                block_on_close=False,
                **auth)
            self.tunnels["gateway"].start()
            self.host = ("localhost", self.tunnels["gateway"].local_bind_port)

        self.tunnels["socket"] = open_tunnel(
            ssh_address_or_host=self.host,
            remote_bind_address=(self.SOCKET_HOST, self.SOCKET_PORT),
            block_on_close=False,
            **auth)
        self.tunnels["socket"].start()

        self.tunnels["ssh"] = open_tunnel(ssh_address_or_host=self.host,
                                          remote_bind_address=(self.SSH_HOST,
                                                               self.SSH_PORT),
                                          block_on_close=False,
                                          **auth)
        self.tunnels["ssh"].start()

        self.host = ("localhost", self.tunnels["socket"].local_bind_port)
Ejemplo n.º 2
0
    def start(self, remote=False):
        if remote:
            REMOTE_SERVER_IP = 'sunfire.comp.nus.edu.sg'
            PRIVATE_SERVER_IP = '137.132.86.228'

            username = input("Enter ssh username: "******"Enter ssh password: ")
            key = 'Sixteen byte key'  #remember to hide
            tunnel1 = sshtunnel.open_tunnel(
                (REMOTE_SERVER_IP, 22),
                remote_bind_address=(PRIVATE_SERVER_IP, 22),
                ssh_username=username,
                ssh_password=password,
                # local_bind_address=('127.0.0.1', 8081),
                block_on_close=False)
            tunnel1.start()
            print('[Tunnel Opened] Tunnel into Sunfire opened ' +
                  str(tunnel1.local_bind_port))
            tunnel2 = sshtunnel.open_tunnel(
                ssh_address_or_host=(
                    'localhost', tunnel1.local_bind_port),  # ssh into xilinx
                remote_bind_address=('127.0.0.1', 10022),  # binds xilinx host
                ssh_username='******',
                ssh_password='******',
                local_bind_address=('127.0.0.1',
                                    10022),  # localhost to bind it to
                block_on_close=False)
            tunnel2.start()
            self.connectAndIdentify('127.0.0.1', 10022, self.dancerID)
        else:
            self.connectAndIdentify('127.0.0.1', 10022, self.dancerID)
Ejemplo n.º 3
0
def main():
    debug = os.environ.get('DEBUG')
    logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
    delay = int(os.environ.get('POLL_PERIOD', '60'))
    server = os.environ['JENKINS_URI']
    status = StatusBoard(pwm=True)
    job_names = [os.environ.get('JENKINS_JOB_%d' % (i + 1)) for i in range(5)]
    job_color = [None for _ in job_names]
    ssh_relay = os.environ.get('SSH_RELAY')
    ssh_user = os.environ.get('SSH_USER')
    ssh_key = os.environ.get('SSH_KEY')

    while True:
        try:
            logging.info("Setting up ssh tunnel via %s@%s", ssh_user,
                         ssh_relay)
            url = urlparse(server)
            host = url.netloc.split(':')[0]
            port = url.port if url.port else 80
            with sshtunnel.open_tunnel(ssh_relay,
                                       ssh_username=ssh_user,
                                       ssh_pkey=ssh_key,
                                       remote_bind_address=(host, port),
                                       local_bind_address=('localhost',
                                                           12345)):

                poll_server(
                    url._replace(netloc='localhost:12345').geturl(), status,
                    job_names, job_color)
                time.sleep(delay)

        except ConnectionError:
            logging.exception("Unable to connect")
            display_warning(delay, status)
            job_color = [None for _ in job_names]
Ejemplo n.º 4
0
 def execute(self, method, **kwargs):
     try:
         print(self.use_ssh)
         print(bool(self.use_ssh))
         conn = None
         result = None
         if self.use_ssh:
             print("DSFKLSDJFL:KDSJFLK:DJF USING SSH")
             with open_tunnel(
                 (self.ssh_host, self.ssh_port),
                     ssh_username=self.ssh_usr,
                     ssh_password=self.ssh_pass,
                     remote_bind_address=(self.svr, self.db_port),
                     local_bind_address=(self.svr,
                                         self.db_port)) as sshserver:
                 conn = psycopg2.connect(host=self.svr,
                                         database=self.dbname,
                                         user=self.usr,
                                         password=self.passcode)
                 result = method(conn, **kwargs)
                 sshserver.stop()
             return result
         else:
             print("GHGHGHGHGGHG NOT using SSH")
             conn = psycopg2.connect(host=self.svr,
                                     database=self.dbname,
                                     user=self.usr,
                                     password=self.passcode,
                                     port=self.db_port)
             return method(conn)
     except (Exception, psycopg.DatabaseError) as error:
         print(error)
     finally:
         if conn is not None:
             conn.close()
Ejemplo n.º 5
0
def main(config, input_stream=None):
    tunnel = None
    try:
        LOGGER.info(config)
        if bool(config.get('use_ssh_tunnel')) == True:
            LOGGER.info(
                f"use_ssh_tunnel is set to true; connecting to {config['redshift_host']}:{config['redshift_port']} via {config['ssh_jump_server']}:{config['ssh_jump_server_port']}"
            )
            tunnel = sshtunnel.open_tunnel(
                (config['ssh_jump_server'], int(
                    config['ssh_jump_server_port'])),
                ssh_username=config['ssh_username'],
                ssh_pkey=config['ssh_private_key_path'],
                ssh_private_key_password=config['ssh_private_key_password']
                if 'ssh_private_key_password' in config else None,
                remote_bind_address=(config['redshift_host'],
                                     int(config['redshift_port'])))
            tunnel.start()
            time.sleep(1)
            config[
                'redshift_host'] = '127.0.0.1'  # rewrite the config to go through the tunnel
            config['redshift_port'] = tunnel.local_bind_port
        else:
            LOGGER.debug(
                f"use_ssh_tunnel is not set or is false; connecting directly to {config['redshift_host']}:{config['redshift_port']}"
            )

        with psycopg2.connect(
                connection_factory=MillisLoggingConnection,
                host=config.get('redshift_host'),
                port=config.get('redshift_port', 5439),
                dbname=config.get('redshift_database'),
                user=config.get('redshift_username'),
                password=config.get('redshift_password')) as connection:
            s3_config = config.get('target_s3')
            s3 = S3(s3_config.get('aws_access_key_id'),
                    s3_config.get('aws_secret_access_key'),
                    s3_config.get('bucket'),
                    s3_config.get('key_prefix'),
                    aws_session_token=s3_config.get('aws_session_token'))

            redshift_target = RedshiftTarget(
                connection,
                s3,
                redshift_schema=config.get('redshift_schema', 'public'),
                logging_level=config.get('logging_level'),
                default_column_length=config.get('default_column_length',
                                                 1000),
                persist_empty_tables=config.get('persist_empty_tables'))

            if input_stream:
                target_tools.stream_to_target(input_stream,
                                              redshift_target,
                                              config=config)
            else:
                target_tools.main(redshift_target)

    finally:
        if tunnel is not None:
            tunnel.stop()
Ejemplo n.º 6
0
 def getTunnel(self):
     tunnel = open_tunnel((self._host, 22),
                          ssh_username='******',
                          ssh_pkey=self._pubkey,
                          remote_bind_address=('127.0.0.1', 8834),
                          local_bind_address=('0.0.0.0', ))
     return tunnel
Ejemplo n.º 7
0
    def _get_connection(self, sql, params, method_instance):
        """
        Creates a connection to the database
        Args:
            sql: The original SQL query.
            params: The original params.
            method_instance: An instance of the method requesting the database connection.

        Returns: The results of the original method instance.
        """
        if self.use_ssh:
            with open_tunnel(
                (self.ssh_host, self.ssh_port),
                    ssh_username=self.ssh_user,
                    ssh_pkey=self.ssh_key_path,
                    remote_bind_address=(self._db_host, self.db_port),
                    local_bind_address=(self.ssh_local_bind_address,
                                        self.ssh_local_bind_port)) as tunnel:
                if self._config.ssh_logging_level:
                    tunnel.logger = create_logger(
                        loglevel=self._config.ssh_logging_level)
                host = tunnel.local_bind_host
                port = tunnel.local_bind_port
                return self._database_connection_sub_method(
                    host, port, method_instance, sql, params)

        else:
            host = self._db_host
            port = self._db_port
            return self._database_connection_sub_method(
                host, port, method_instance, sql, params)
def query_from_mongodb(db_name,
                       collection_name,
                       query_conditions,
                       columns,
                       conn_info=config.mongo_conn_info):
    """
    在mongodb中查询数据
    :param db_name:
    :param collection_name:
    :param query_conditions:
    :param columns: 指定返回的列。(未生效,待调试)
    :param conn_info:
    :return:
    """
    with sshtunnel.open_tunnel(
            ssh_address_or_host=(config.base_ip, 22),
            ssh_password=config.ssh_root_password,
            ssh_username='******',
            remote_bind_address=(conn_info['host'], conn_info['port']),
            local_bind_address=('0.0.0.0', conn_info['port'])) as tunnel:
        client = pymongo.MongoClient(port=conn_info['port'],
                                     username=conn_info['username'],
                                     password=conn_info['passwd'])
        db = client[db_name]
        collection = db[collection_name]
        res = []
        for i in collection.find(query_conditions, columns):
            # res.append(list(i.values()))
            res.append(i)
        # print(res)
        return res
Ejemplo n.º 9
0
        def wrapper(*args, **kwargs):
            try:
                remote_host, remote_port = query_runner.host, query_runner.port
            except NotImplementedError:
                raise NotImplementedError(
                    "SSH tunneling is not implemented for this query runner yet."
                )

            stack = ExitStack()
            try:
                bastion_address = (details["ssh_host"],
                                   details.get("ssh_port", 22))
                remote_address = (remote_host, remote_port)
                auth = {
                    "ssh_username": details["ssh_username"],
                    **settings.dynamic_settings.ssh_tunnel_auth(),
                }
                server = stack.enter_context(
                    open_tunnel(bastion_address,
                                remote_bind_address=remote_address,
                                **auth))
            except Exception as error:
                raise type(error)("SSH tunnel: {}".format(str(error)))

            with stack:
                try:
                    query_runner.host, query_runner.port = server.local_bind_address
                    result = f(*args, **kwargs)
                finally:
                    query_runner.host, query_runner.port = remote_host, remote_port

                return result
Ejemplo n.º 10
0
    def get_deployment_target_client(target: MachineDeploymentBlock):
        with open(target.bastion_ssh_key_path,
                  'r') as bastion_key_file_handler:
            bastion_key = paramiko.RSAKey.from_private_key(
                StringIO(bastion_key_file_handler.read()))
        with open(target.deployment_target_ssh_key_path,
                  'r') as bastion_key_file_handler:
            deployment_target_key = paramiko.RSAKey.from_private_key(
                StringIO(bastion_key_file_handler.read()))

        with open_tunnel(ssh_address_or_host=(target.bastion_address, 22),
                         remote_bind_address=(target.deployment_target_address,
                                              22),
                         ssh_username=target.bastion_user_name,
                         ssh_pkey=bastion_key) as tunnel:
            logger.info(
                f"Opened SSH tunnel to {target.deployment_target_address} via {target.bastion_address} "
            )

            with paramiko.SSHClient() as client:
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect('localhost',
                               port=tunnel.local_bind_port,
                               username=target.deployment_target_user_name,
                               pkey=deployment_target_key,
                               compress=True,
                               banner_timeout=60)

                yield client
    def __enter__(self):
        from sshtunnel import open_tunnel

        wrapped_conn = get_hook(self.wrapped_conn_id)
        self.tunnel = open_tunnel(
            (self.remote_ip, self.remote_port),
            ssh_username=self.ssh_username,
            ssh_pkey=self.ssh_pkey,
            ssh_password=self.ssh_password,
            remote_bind_address=(wrapped_conn.conn_params.host,
                                 wrapped_conn.conn_params.port),
        )
        self.tunnel.start()
        self.tunneled_conn = wrapped_conn.__class__.__new__(
            wrapped_conn.__class__)
        self.tunneled_conn.__init__(
            ConnectionParams(
                conn_type=wrapped_conn.conn_params.conn_type,
                host=self.tunnel.local_bind_host,
                port=self.tunnel.local_bind_port,
                login=wrapped_conn.conn_params.login,
                password=wrapped_conn.conn_params.password,
                extra=wrapped_conn.conn_params.extra,
            ))
        return self.tunneled_conn.__enter__()
Ejemplo n.º 12
0
def engage(SERVER, PORT, USER, PASSWD):
    with open_tunnel((SERVER, PORT),
                     ssh_username=USER,
                     ssh_password=PASSWD,
                     remote_bind_address=("127.0.0.1", 8080)) as server:
        print(server.local_bind_port)
        while not END_SERVER:
            sleep(1)
Ejemplo n.º 13
0
def create_tunnel(tunnel_host, tunnel_port, tunnel_user, tunnel_password,
                  pg_host, pg_port):
    server = sshtunnel.open_tunnel((tunnel_host, int(tunnel_port)),
                                   ssh_username=tunnel_user,
                                   ssh_password=tunnel_password,
                                   remote_bind_address=(pg_host, int(pg_port)))
    server.start()
    port = server.local_bind_port
    return port
Ejemplo n.º 14
0
 def connect(self, service_host, port):
     DEBUG('Create ssh tunnel:', self.user, self.passwd, self.host, 'bind:', service_host, port)
     self.tunnel = sshtunnel.open_tunnel(
         self.host, ssh_username=self.user, ssh_password=self.passwd,
         remote_bind_address=(service_host, port),
         set_keepalive=0.5,
         #debug_level='TRACE'
         )
     return self.tunnel
Ejemplo n.º 15
0
def bastion_host():
    with sshtunnel.open_tunnel(
        (bastion_host_url, bastion_host_port),
            ssh_username="******",
            remote_bind_address=(nas_url, nas_port),
            local_bind_address=(locally_bound_ip,
                                locally_bound_port)) as tunnel:
        logger.info('Opening tunnel')
        yield tunnel
Ejemplo n.º 16
0
    async def _connect(self):
        """Creates a connection to the database, either directly or through a tunnel"""
        log.spam("Attempting to connect to local database")
        try:
            self.dbPool = await aiomysql.create_pool(
                user=DBUser,
                password=DBPass,
                host="127.0.0.1",
                port=3306,
                auth_plugin="mysql_native_password",
                maxsize=10)
        except:
            # Probably working on a dev machine, create a tunnel
            log.warning(
                "Unable to connect to database, attempting to create SSH Tunnel"
            )
            self.tunnel = sshtunnel.open_tunnel(
                (serverAddress, serverPort),
                ssh_username=sshUser,
                ssh_pkey="opensshkey.ppk",
                remote_bind_address=(localAddress, localPort),
                local_bind_address=(localAddress, localPort),
                logger=utilities.getLog("tunnel", logging.CRITICAL))
            self.tunnel.start()
            while not self.tunnel.is_active:
                # Wait for the tunnel to be considered active
                time.sleep(0.1)
            log.spam(
                f"Connected to DB Server: {self.tunnel.is_active}. "
                f"LocalAddr: {self.tunnel.local_bind_host}:{self.tunnel.local_bind_port}"
            )
            log.debug("Attempting to connect to tunneled database")
            try:
                self.dbPool = await aiomysql.create_pool(
                    user=DBUser,
                    password=DBPass,
                    host=self.tunnel.local_bind_host,
                    port=self.tunnel.local_bind_port,
                    auth_plugin="mysql_native_password",
                    maxsize=10,
                )
            except Exception as e:
                log.critical(f"Failed to connect to db, aborting startup: {e}")
                exit(1)

        # Configure db to accept emoji inputs (i wish users didnt do this, but i cant stop em)
        await self.execute('SET NAMES utf8mb4;')
        await self.execute('SET CHARACTER SET utf8mb4;')
        await self.execute('SET character_set_connection=utf8mb4;')

        databases = await self.execute("SHOW SCHEMAS")
        log.info(
            f"Database connection established. {len(databases)} schemas found")
        return True
Ejemplo n.º 17
0
 def ssh_tunnel(ip, port):
     """Return a SSH tunnel to the Mongo db
     """
     tunnel = open_tunnel(block_on_close=False,
                          ssh_address_or_host='jump01.slunow.bskyb.com',
                          ssh_port=22,
                          ssh_username=os.getenv('q'),
                          ssh_password=os.getenv('a'),
                          remote_bind_address=(ip, port))
     tunnel.start()
     return tunnel
Ejemplo n.º 18
0
 def start_tunnel(self, user, password):
     tunnel1 = sshtunnel.open_tunnel(
         ('sunfire.comp.nus.edu.sg', 22), #host address for ssh, 22
         remote_bind_address=('137.132.86.243', 22), #xilinx address to bind to localhost port
         ssh_username=user,
         ssh_password=password,
         block_on_close=False
         )
     tunnel1.start()
     print('[Tunnel Opened] Tunnel into Sunfire opened' + str(tunnel1.local_bind_port))
     tunnel2 = sshtunnel.open_tunnel(
         ssh_address_or_host=('localhost', tunnel1.local_bind_port), #ssh into xilinx
         remote_bind_address=('127.0.0.1', 8083), #binds xilinx host
         ssh_username='******',
         ssh_password='******',
         local_bind_address=('127.0.0.1', 8083), #localhost to bind it to
         block_on_close=False
         )
     tunnel2.start()
     print('[Tunnel Opened] Tunnel into Xilinx opened')
Ejemplo n.º 19
0
async def main():
    with open_tunnel((REMOTE_SERVER_IP, 22),
                     ssh_username=REMOTE_SERVER_USER,
                     ssh_pkey=REMOTE_SERVER_PUBKEY,
                     remote_bind_address=('127.0.0.1', REMOTE_BIND_PORT),
                     local_bind_address=('0.0.0.0', )) as tunnel:
        async with aiohttp.ClientSession() as session:
            async with session.get(
                    f"http://127.0.0.1:{tunnel.local_bind_port}/v1/policy/list"
            ) as response:
                if response.status == 200:
                    policies = json.loads(await response.text())
                    print(json.dumps(policies, indent=2))
Ejemplo n.º 20
0
    def get_deployment_target_client_context(
            block_to_deploy: MachineDeploymentBlock):
        with open(block_to_deploy.deployment_target_ssh_key_path,
                  'r') as ssh_key_file_handler:
            deployment_target_key = paramiko.RSAKey.from_private_key(
                StringIO(ssh_key_file_handler.read()))

        if block_to_deploy.bastion_address is None:
            with paramiko.SSHClient() as client:
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                logger.info(
                    f"Connecting directly to {block_to_deploy.deployment_target_address}, "
                    f"using key at {block_to_deploy.deployment_target_ssh_key_path}"
                )
                client.connect(
                    block_to_deploy.deployment_target_address,
                    port=22,
                    username=block_to_deploy.deployment_target_user_name,
                    pkey=deployment_target_key,
                    compress=True,
                    banner_timeout=60)
                yield client
            return

        with open(block_to_deploy.bastion_ssh_key_path,
                  'r') as bastion_key_file_handler:
            bastion_key = paramiko.RSAKey.from_private_key(
                StringIO(bastion_key_file_handler.read()))

        with open_tunnel(
                ssh_address_or_host=(block_to_deploy.bastion_address, 22),
                remote_bind_address=(block_to_deploy.deployment_target_address,
                                     22),
                ssh_username=block_to_deploy.bastion_user_name,
                ssh_pkey=bastion_key) as tunnel:
            logger.info(
                f"Opened SSH tunnel to {block_to_deploy.deployment_target_address} via {block_to_deploy.bastion_address} "
            )

            with paramiko.SSHClient() as client:
                client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                client.connect(
                    'localhost',
                    port=tunnel.local_bind_port,
                    username=block_to_deploy.deployment_target_user_name,
                    pkey=deployment_target_key,
                    compress=True,
                    banner_timeout=60)

                yield client
Ejemplo n.º 21
0
def open_sshtunnel(thread):
    with sshtunnel.open_tunnel(
        ("proxy-vm.ddns.net", 22),
            ssh_username="******",
            ssh_pkey="Public_Key.pem",
            remote_bind_address=("0.0.0.0", 8000),
            local_bind_address=('127.0.0.1', 54321)) as tunnel:
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        #client.connect('127.0.0.1', 4444)
        #do some operations with client session
        #client.close()
        #source: https://pypi.org/project/sshtunnel/
        thread.join()
Ejemplo n.º 22
0
 def test_local_side(self):
     loc_port = random.randint(21000, 30000)
     rem_host = '192.168.1.1'
     rem_port = 443
     print 'Trying to log in to tunnel'
     tunnel = sshtunnel.open_tunnel(gateway = 'localhost',
                                    ssh_port = SSH_PORT,
                          ssh_username = sshserver.SSH_CREDENTIALS[0],
                          ssh_password = sshserver.SSH_CREDENTIALS[1],
                          remote_bind_address_list=(rem_host, rem_port),
                          local_bind_address_list=('', loc_port))
     tunnel.start()
     tunnel._transport.open_session()
     self.assertEqual(tunnel.local_bind_ports, [loc_port])
     tunnel.stop()
Ejemplo n.º 23
0
def sshConnect():
    base_path = Path(__file__).parent
    file_path = (base_path / "misato")
    __file = str(file_path)

    sshtunnel.SSH_TIMEOUT = sshtunnel.TUNNEL_TIMEOUT = 10.0

    server = sshtunnel.open_tunnel(
        ('168.61.73.89', 31415),
        ssh_username='******',
        ssh_pkey=__file,
        ssh_private_key_password ='******',
        remote_bind_address=('127.0.0.1', 27017)
    )
    return server
Ejemplo n.º 24
0
def sshtunconnect(address):
    """
     Устанавливает соединение с пробросом порта по заданному IP адресу ( который был найден из JSON объекта) ранее и
     передан в функцию в качестве параметра.
    """
    server = open_tunnel(
        publicipadress,
        ssh_username="******",
        #       ssh_password="******",
        ssh_pkey="srv.key",  # можно использовать вместо пароля файл ключа
        remote_bind_address=address,
        local_bind_address=('localhost', 2222
                            )  # адрес и порт куда происходит проброс
    )
    server.start()
    print(server.local_bind_port)
Ejemplo n.º 25
0
 def test_open_tunnel(self):
     """ Test wrapper method mainly used from CLI """
     server = sshtunnel.open_tunnel(
         (self.saddr, self.sport),
         ssh_username=SSH_USERNAME,
         ssh_password=SSH_PASSWORD,
         remote_bind_address=(self.eaddr, self.eport),
         logger=self.log,
         ssh_config_file=None,
     )
     self.assertEqual(server.ssh_host, self.saddr)
     self.assertEqual(server.ssh_port, self.sport)
     self.assertEqual(server.ssh_username, SSH_USERNAME)
     self.assertEqual(server.ssh_password, SSH_PASSWORD)
     self.assertEqual(server.logger, self.log)
     self._test_server(server)
def insert_to_mongodb(db_name,
                      collections_and_conditions,
                      conn_info=config.mongo_conn_info):
    with sshtunnel.open_tunnel(
            ssh_address_or_host=(config.base_ip, 22),
            ssh_password=config.ssh_root_password,
            ssh_username='******',
            remote_bind_address=(conn_info['host'], conn_info['port']),
            local_bind_address=('0.0.0.0', conn_info['port'])) as tunnel:
        client = pymongo.MongoClient(port=conn_info['port'],
                                     username=conn_info['username'],
                                     password=conn_info['passwd'])
        db = client[db_name]
        for collection_name, insert_condition in collections_and_conditions.items(
        ):
            collection = db[collection_name]
            collection.insert_one(insert_condition)
Ejemplo n.º 27
0
    def tunneling(self,
                  host,
                  host_port,
                  pem_key_path,
                  remote_ip,
                  remote_port,
                  user="******",
                  local_ip="127.0.0.1",
                  local_port=10022):
        """ssh tunneling to private server that don't have public ip address"""

        return sshtunnel.open_tunnel(
            (host, host_port),
            ssh_username=user,
            ssh_pkey=pem_key_path,
            remote_bind_address=(remote_ip, remote_port),
            local_bind_address=(local_ip, local_port))
Ejemplo n.º 28
0
    def test_remote_side(self):
        rem_port = random.randint(21000, 30000)
        rem_host = socket.gethostbyname_ex(socket.gethostname())[0]
        print 'Trying to log in to tunnel'
        tunnel = sshtunnel.open_tunnel(gateway = 'localhost',
                                       ssh_port = SSH_PORT,
                             ssh_username = sshserver.SSH_CREDENTIALS[0],
                             ssh_password = sshserver.SSH_CREDENTIALS[1],
                             remote_bind_address_list=(rem_host, rem_port))
        tunnel.start()
#        tunnel._transport.open_channel(kind='session')
        tunnel._transport.open_session()
        self.assertEqual(tunnel.remote_bind_ports, [rem_port])
        self.assertEqual(tunnel.remote_bind_hosts, [rem_host])
#        chan.send('dir')
#        print chan.recv(1024)
        print 'Stopping tunnel'
        tunnel.stop()
Ejemplo n.º 29
0
    def ssh_tunnel(self) -> SSHTunnelForwarder:
        """
        Get SSH Tunnel instance
        :return:
        :rtype:
        """
        if self._ssh_tunnel is None and self._use_ssh:
            self.logger.debug(f"Starting SSH Tunnel {self._ssh_ip}:{self._ssh_port}")
            self.logger.debug(f"Username: {self._ssh_username}")
            self.logger.debug(f"Password: {''.join('*' for x in self._ssh_password)}")

            self._ssh_tunnel = sshtunnel.open_tunnel(
                (self._ssh_ip, self._ssh_port),
                ssh_username=self._ssh_username,
                ssh_password=self._ssh_password,
                remote_bind_address=(self._remote_bind_ip, self._remote_bind_port),
            )

        return self._ssh_tunnel
Ejemplo n.º 30
0
    def run(self):
        logger.info("Establishing SSH tunnel...")
        local_args = {} if not self.local_port else {'local_bind_address': ('0.0.0.0', self.local_port)}
        with sshtunnel.open_tunnel(
                (self.ssh_params.host, self.ssh_params.port),
                ssh_username=self.ssh_params.user,
                ssh_pkey=self.ssh_params.pkey_file,
                ssh_private_key_password=self.ssh_params.pkey_pass,
                remote_bind_address=(self.remote_server, self.remote_port),
                **local_args
        ) as tunnel:
            self.local_port = tunnel.local_bind_port
            self.is_running = True
            logger.info("SSH tunnel established, port: %s" % self.local_port)

            while not self.terminating:
                time.sleep(0.5)

            self.is_running = False
            logger.info("Closing SSH tunnel")
    def __init__(self, device, adb: ADB):
        self._adb = adb
        self._device = device
        host, port = device.serial.split(":")
        atexit.register(self.close)

        self._tunnel = sshtunnel.open_tunnel(
            self._adb.ssh_tunnel.ssh_host,
            self._adb.ssh_tunnel.ssh_port,
            ssh_username=self._adb.ssh_tunnel.ssh_username,
            ssh_password=self._adb.ssh_tunnel.ssh_password,
            remote_bind_address=(host, int(port))
        )

        self._tunnel.start()
        self._ui_automator = UIAutomatorDevice(
            device.serial,
            adb_server_host="127.0.0.1",
            adb_server_port=self._tunnel.local_bind_port
        )
Ejemplo n.º 32
0
    def init_tunnels(self, system=None):
        """
        Initialize SSH tunnels using ``sshtunnel`` and ``paramiko`` libraries.

        Arguments:
        - system

            Type: string

            Default: ``None``

            Description:
            system to initialize the tunnels. If nothing given it initializes
            tunnels for all systems in ``self.systems``.

        Return:

            ``SSHTunnelForwarder`` instance (non-started) with all tunnels
            already established
        """
        if not self._check_if_using_gateway(system):
            return
        self.logger.info('Initializing tunnels')
        if not self.conf:
            self.conf = arguments.read_config(self.settings_file)

        jumpbox_addr = self.conf.get('GATEWAY', 'ip_or_hostname')
        jumpbox_port = self.conf.getint('GATEWAY', 'ssh_port')
        rbal = []
        lbal = []
        tunnelports = {}
        systems = [system] if system else self.systems
        sshtunnel.SSH_TIMEOUT = arguments.DEFAULT_SSH_TIMEOUT

        for _sys in systems:
            rbal.append((self.conf.get(_sys, 'ip_or_hostname'),
                         self.conf.getint(_sys, 'ssh_port')))
            lbal.append(('', self.conf.getint(_sys, 'tunnel_port')))
        if len(tunnelports) != len(set(tunnelports.values())):
            self.logger.error('Local tunnel ports MUST be different: {0}'
                              .format(tunnelports))
            raise sshtunnel.BaseSSHTunnelForwarderError
        try:
            pwd = self.conf.get('GATEWAY', 'password').strip("\"' ") or None \
                if self.conf.has_option('GATEWAY', 'password') else None
            pkey = self.conf.get('GATEWAY', 'identity_file').strip("\"' ") \
                or None if self.conf.has_option('GATEWAY', 'identity_file') \
                else None
            user = self.conf.get('GATEWAY', 'username') or None \
                if self.conf.has_option('GATEWAY', 'username') else None
            self.server = sshtunnel.open_tunnel(
                ssh_address_or_host=(jumpbox_addr, jumpbox_port),
                ssh_username=user,
                ssh_password=pwd,
                remote_bind_addresses=rbal,
                local_bind_addresses=lbal,
                threaded=True,
                logger=self.logger,
                ssh_pkey=pkey,
                ssh_private_key_password=pwd,
                set_keepalive=15.0,
                allow_agent=False,
                mute_exceptions=True,
                skip_tunnel_checkup=False,
            )
            self.server.is_use_local_check_up = True  # Check local side
            self._start_server()
            assert self.server.is_alive
            # Add the system<>port bindings to the return object
            self.server.tunnelports = dict(
                list(zip(systems, self.server.local_bind_ports))
            )
            self.logger.debug('Registered tunnels: {0}'
                              .format(self.server.tunnelports))
        except (sshtunnel.BaseSSHTunnelForwarderError, AssertionError):
            self.logger.error('{0}Could not open connection to remote server: '
                              '{1}:{2}'.format(
                                  '{0} | '.format(system) if system else '',
                                  jumpbox_addr,
                                  jumpbox_port
                              ))
            raise sshtunnel.BaseSSHTunnelForwarderError