示例#1
0
async def run_socks(ssh_host,
                    ssh_user,
                    ssh_password,
                    socks_host,
                    socks_port,
                    _timeout=10,
                    keepalive_interval=10):
    try:
        conn, client = await asyncio.wait_for(
            asyncssh.create_connection(
                client_factory=None,
                host=ssh_host,
                username=ssh_user,
                password=ssh_password,
                known_hosts=None,
                agent_path=None,
                keepalive_interval=keepalive_interval,
            ), _timeout)
    except TimeoutError:
        logger.error("Failed start socks5 server, TimeoutError.")
        return
    listener = await conn.forward_socks(socks_host, socks_port)
    logger.info("listen on port: {port} for {host}".format(
        port=listener.get_port(), host=socks_host))
    await asyncio.sleep(1)
    data = await get_external_ip(socks_host=socks_host, socks_port=socks_port)
    if not data:
        conn.close()
        logger.error("Failed start socks5 server.")
        return
    await conn.wait_closed()
示例#2
0
    async def run_command(self, cmd, showout=True, die=True, env={}):
        if self._client is None or self._client.conn is None:
            self.logger.debug("create new connection to {}:{}".format(
                self.addr, self.port))

            try:
                _, self._client = await asyncio.wait_for(
                    asyncssh.create_connection(
                        client_factory=SSHClient,
                        host=self.addr,
                        username=self.login,
                        password=self.password,
                        known_hosts=None,
                        agent_forwarding=self.forward_agent,
                        client_keys=list(self.key_filename),
                        passphrase=self.passphrase),
                    timeout=self.timeout)
            except asyncio.TimeoutError as ex:
                self.logger.error("connection to {}:{} timed out".format(
                    self.addr, self.port))
                raise ex

        chan, session = await self._client.conn.create_session(
            session_factory=functools.partial(SSHClientSession,
                                              showout=showout),
            command=cmd,
            env=env)
        await chan.wait_closed()

        return session.exit_status, session.stdout, session.stderr
示例#3
0
def run_client():
    conn, client = yield from asyncssh.create_connection(None, 'localhost')
    chan, session = yield from conn.create_session(MySSHClientSession, 'env',
                                                   env={ 'LANG': 'en_GB',
                                                         'LC_COLLATE': 'C'})
    yield from chan.wait_closed()
    conn.close()
示例#4
0
 def _ensure_connected(self, forward_remote_port=None):
     with (yield from self._connecting):
         if forward_remote_port:
             self._forwarded_remote_ports.append(forward_remote_port)
         if self.jumphost:
             yield from self.jumphost._ensure_connected()
             tunnel = self.jumphost.conn
         else:
             tunnel = None
         if self._connected.is_set():
             if forward_remote_port:
                 args, kwargs = forward_remote_port
                 listener = yield from self.conn.\
                         forward_remote_port(*args, **kwargs)
                 # TODO: cancel it when client closed
                 self.loop.create_task(listener.wait_closed())
             return
         LOG.debug("Connecting %s@%s (keys %s) (via %s)" %
                   (self.username, self.hostname, self.keys, self.jumphost))
         self.conn, self.client = yield from asyncssh.create_connection(
             functools.partial(SSHClient, self),
             self.hostname,
             username=self.username,
             known_hosts=None,
             password=self.password,
             client_keys=self.keys,
             port=self.port,
             tunnel=tunnel)
         for args, kwargs in self._forwarded_remote_ports:
             try:
                 yield from self.conn.forward_remote_port(*args, **kwargs)
             except Exception as ex:
                 print(ex)
         LOG.debug("Connected %s@%s" % (self.username, self.hostname))
示例#5
0
文件: sshproxy.py 项目: JawaGL/apssh
    async def _connect_direct(self):
        """
        The code for connecting to the first ssh hop
        (i.e. when self.gateway is None)
        """
        assert self.gateway is None

        # pylint: disable=c0111
        class ClientClosure(_VerboseClient):
            # it is crucial that the first param here is *NOT* called self
            def __init__(client_self, *args, **kwds):  # pylint: disable=e0213
                _VerboseClient.__init__(client_self,
                                        self,
                                        direct=True,
                                        *args,
                                        **kwds)

        self.debug_line("SSH direct connecting")
        # second returned value is client, but is unused
        self.conn, _ = \
            await asyncio.wait_for(
                asyncssh.create_connection(
                    ClientClosure, self.hostname, port=self.port,
                    username=self.username,
                    known_hosts=self.known_hosts, client_keys=self.keys
                ),
                timeout=self.timeout)
示例#6
0
    def _lazy_connect(self):
        """
        Open a connection to the SSH server if necessary.
        """
        if self._conn is not None:
            return

        while self._conn is None:
            try:
                self._conn, _ = yield from asyncssh.create_connection(lambda: self, self._host, **self._login)
            except TimeoutError:
                self.log.debug('Timeout! Sleeping for a bit.')
                asyncio.sleep(60)

        self._stdin, self._stdout, _ = yield from self._conn.open_session(encoding=None)

        # If auto-enable is enabled, the prompt will end with #; otherwise it will end with >
        result = yield from self.collect_until_prompt(b'^.+[#>] $')

        # TODO: the result=None case is not handled!
        if result and result[0].endswith('> '):
            yield from self._enable()

        self._send_cmd('terminal pager 0')
        yield from self.collect_until_prompt(PRIV_PROMPT)
示例#7
0
文件: main.py 项目: sdfmmbi/sshame
    async def test_keys_on_single_target(self, host_address, host_port,
                                         username, keys):
        log_id = f"{username}@{host_address}:{host_port}"
        async with self.sem:
            _pkssh = self.PublicKeySSHClient(self.db, keys, host_address,
                                             host_port, username)

            def client_factory():
                return _pkssh

            valid_creds = 0
            keys_consumed = 0
            log.debug(f'[*] [{log_id}] Remaining keys: {len(keys)}')
            while True:
                conn = None
                try:
                    log.debug(f'[*] [{log_id}] Connecting')
                    conn, client = await asyncio.wait_for(
                        asyncssh.create_connection(client_factory,
                                                   host_address,
                                                   port=host_port,
                                                   username=username,
                                                   known_hosts=None,
                                                   client_keys=None,
                                                   x509_trusted_certs=None,
                                                   client_host_keys=None),
                        timeout=self.timeout)
                    log.debug(f'[*] [{log_id}] Connection created')
                    valid_creds += 1
                except asyncio.TimeoutError:
                    log.warning(f'[{log_id}] Time out')
                    return valid_creds
                except Exception as ex:
                    msg = str(ex)
                    if not _pkssh.keys_left():
                        log.debug(
                            f'[{log_id}] All {_pkssh.keys_to_test} keys tested.'
                        )
                        return valid_creds  # Exception("No more keys")
                    if (_pkssh.keys_consumed() == keys_consumed):
                        log.info(f'[{log_id}] No keys consumed, but: {msg}')
                        return valid_creds
                    keys_consumed = _pkssh.keys_consumed()
                    ignore = [
                        'Permission denied', 'Too many authentication',
                        'Connection reset by peer',
                        'The maximum number of authentication attempts'
                    ]
                    if not any(x in msg for x in ignore):
                        log.warning(f'[{log_id}] {msg}')
                        return valid_creds
                    if not _pkssh.key_fingerprint:
                        log.debug(
                            f'[{log_id}] All {_pkssh.keys_to_test} keys tested..'
                        )
                        return valid_creds  # Exception("No more keys")
                finally:
                    if conn:
                        conn.abort()
示例#8
0
def run_client():
    conn, client = yield from asyncssh.create_connection(MySSHClient, 'localhost')

    with conn:
        chan, session = yield from conn.create_session(MySSHClientSession, 'ls abc')
        yield from chan.wait_closed()

    yield from conn.wait_closed()
示例#9
0
    def create_connection(self, client_factory, **kwargs):
        """Create a connection to the test server"""

        return (yield from asyncssh.create_connection(client_factory,
                                                      self._server_addr,
                                                      self._server_port,
                                                      loop=self.loop,
                                                      **kwargs))
示例#10
0
def run_client():
    conn, client = yield from asyncssh.create_connection(None, 'localhost')
    chan, session = yield from conn.create_session(MySSHClientSession,
                                                   'echo $TERM; stty size',
                                                   term_type='xterm-color',
                                                   term_size=(80, 24))
    yield from chan.wait_closed()
    conn.close()
示例#11
0
def run_client():
    conn, client = yield from asyncssh.create_connection(
        MySSHClient, 'localhost')

    with conn:
        chan, session = yield from conn.create_session(MySSHClientSession,
                                                       'ls abc')
        yield from chan.wait_closed()
示例#12
0
    async def asyncScan(self, gw, silent):

        #This inner class access the endpoint through the "endpoint" var as "self" keywork is changed
        endpoint = self

        class ScanSSHClient(asyncssh.SSHClient):
            def connection_made(self, conn):
                endpoint.setReachable(True)

            def auth_banner_received(self, msg, lang):
                print(msg)

            def public_key_auth_requested(self):
                endpoint.addAuth("privkey")
                return None

            def password_auth_requested(self):
                endpoint.addAuth("password")
                return None

            def kbdint_auth_requested(self):
                endpoint.addAuth("kbdint")
                return None

            def auth_completed(self):
                pass

        self.setScanned(True)
        try:
            conn, client = await asyncio.wait_for(asyncssh.create_connection(
                ScanSSHClient,
                self.getIp(),
                port=self.getPort(),
                tunnel=gw,
                known_hosts=None,
                username="******"),
                                                  timeout=3.0)
        except asyncssh.Error as e:
            #Permission denied => expected behaviour
            if e.code == 14:
                pass
            else:
                print("asyncssh Error: " + str(e))
                return False
        except asyncio.TimeoutError:
            self.setReachable(False)
            self.save()
            if not silent:
                print("Timeout")
            return False
        try:
            conn.close()
        except:
            pass
        if not silent:
            print("Done")
        self.save()
        return True
示例#13
0
def run_client():
    conn, client = yield from asyncssh.create_connection(None, 'localhost')
    server = yield from conn.create_server(connection_requested, '', 8888,
                                           encoding='utf-8')

    if server:
        yield from server.wait_closed()
    else:
        print('Listener couldn''t be opened.', file=sys.stderr)
示例#14
0
    def create_connection(self, client_factory, loop=(), **kwargs):
        """Create a connection to the test server"""

        if loop is ():
            loop = self.loop

        return (yield from asyncssh.create_connection(client_factory,
                                                      self._server_addr,
                                                      self._server_port,
                                                      loop=loop, **kwargs))
示例#15
0
def run_client():
    conn, client = yield from asyncssh.create_connection(None, 'localhost')
    stdin, stdout, stderr = yield from conn.open_session('bc')

    for op in ['2+2', '1*2*3*4', '2^32']:
        stdin.write(op + '\n')
        result = yield from stdout.readline()
        print(op, '=', result, end='')

    conn.close()
示例#16
0
def run_client():
    conn, client = yield from asyncssh.create_connection(None, 'localhost')
    chan, session = yield from conn.create_connection(MySSHTCPSession,
                                                      'www.google.com', 80)

    # By default, TCP connections send and receive bytes
    chan.write(b'HEAD / HTTP/1.0\r\n\r\n')
    chan.write_eof()

    yield from chan.wait_closed()
    conn.close()
示例#17
0
文件: ssh.py 项目: redixin/rally-ci
 def _ensure_connected(self):
     with (yield from self._connecting):
         if self._connected.is_set():
             return
         LOG.debug("Connecting %s@%s with keys %s" % (self.username,
                                                      self.hostname,
                                                      self.keys))
         self.conn, self.client = yield from asyncssh.create_connection(
             functools.partial(SSHClient, self), self.hostname,
             username=self.username, known_hosts=None,
             client_keys=self.keys, port=self.port)
         LOG.debug("Connected %s@%s" % (self.username, self.hostname))
示例#18
0
文件: server.py 项目: ronf/asyncssh
    def create_connection(self, client_factory, loop=(),
                          gss_host=None, **kwargs):
        """Create a connection to the test server"""

        if loop == ():
            loop = self.loop

        return (yield from asyncssh.create_connection(client_factory,
                                                      self._server_addr,
                                                      self._server_port,
                                                      loop=loop,
                                                      gss_host=gss_host,
                                                      **kwargs))
def run_client():
    conn, client = yield from asyncssh.create_connection(None, 'localhost')
    reader, writer = yield from conn.open_connection('www.google.com', 80)

    # By default, TCP connections send and receive bytes
    writer.write(b'HEAD / HTTP/1.0\r\n\r\n')
    writer.write_eof()

    # We use sys.stdout.buffer here because we're writing bytes
    response = yield from reader.read()
    sys.stdout.buffer.write(response)

    conn.close()
示例#20
0
 def get_conn(self, host):
     try:
         return self.conn_cache[host]
     except KeyError:
         self.conn_cache[host] = asyncio.ensure_future(
             asyncssh.create_connection(
                 None,
                 host,
                 username=self.username,
                 known_hosts=None,
                 client_keys=self.get_keys(),
             )
         )
         return self.conn_cache[host]
示例#21
0
 async def connect(self, timeout=None):
     try:
         # for private keys
         # also pass here client_keys = [some_list]
         # see http://asyncssh.readthedocs.org/en/latest/api.html#specifyingprivatekeys
         self.conn, self.client = await asyncio.wait_for(
             asyncssh.create_connection(
                 MySSHClient, self.hostname, username=self.username, known_hosts=None
             ),
             timeout = timeout)
         return True
     except (OSError, asyncssh.Error, asyncio.TimeoutError) as e:
         #await self.node.feedback('ssh_status', 'connect failed')
         #print('SshProxy.connect failed: {}'.format(e))
         self.conn, self.client = None, None
         return False
示例#22
0
    def _ssh_runner(self, connection, task, killers, command, streams):
        if streams and streams['stdin'].channel._session:
            stdin, stdout, stderr, conn = streams['stdin'], streams[
                'stdout'], streams['stderr'], streams['connection']
            log.debug('Reuse ssh connection')
        else:
            try:
                ip, port = parse_host(connection['ip'], 22)
                conn, client = yield from asyncssh.create_connection(
                    None,
                    host=ip,
                    port=port,
                    username=connection.get('login'),
                    password=connection.get('password'),
                    server_host_keys=None)
                stdin, stdout, stderr = yield from conn.open_session(
                    term_type='xterm-color', term_size=(80, 24))
            except asyncio.CancelledError:
                log.error("Cannot open SSH-session", exc_info=False)
                self.db_log.error("Не удалось открыть ssh соединение", str(ex),
                                  'connection', connection['_id'])
                return -999, "", {}
            except Exception as ex:
                log.error("Cannot open SSH-session", exc_info=True)
                self.db_log.error("Не удалось открыть ssh соединение", str(ex),
                                  'connection', connection['_id'])
                return -999, "", {}

            streams = dict(stdin=stdin,
                           stdout=stdout,
                           stderr=stderr,
                           connection=conn)
            log.debug('Open new ssh connectionm host={}'.format(
                connection.get('ip')))
            killers.append(conn.close)

        try:
            stdin.write("{}\r".format(command))
            results = yield from self._read_ssh_with_ttl(stdout)
        except:
            log.error("Cannot communicate with SSH-session", exc_info=True)
            return -999, "", {}

        log.debug('Run ssh command "{}", output:\n--\n{}--'.format(
            command, results))

        return 0, results, streams
示例#23
0
    async def _connect_direct(self):
        """
        The code for connecting to the first ssh hop (i.e. when self.gateway is None)
        """
        assert self.gateway is None

        class client_closure(VerboseClient):
            def __init__(client_self, *args, **kwds):
                VerboseClient.__init__(client_self, self, direct=True, *args, **kwds)

        self.debug_line("SSH direct connecting")
        self.conn, client = \
            await asyncio.wait_for( 
                asyncssh.create_connection(
                    client_closure, self.hostname, port=self.port, username=self.username,
                    known_hosts=self.known_hosts, client_keys=self.keys
                ),
                timeout = self.timeout)
示例#24
0
def asyncssh_connect(host, port, passwords):
    last_error = None
    for password in itertools.chain(passwords.get(host, []),
                                    passwords.get(ALL_HOSTS, [])):
        try:
            conn, _ = yield from create_connection(None,
                                                   host,
                                                   port,
                                                   username='******',
                                                   password=password,
                                                   known_hosts=None)
            break
        except asyncssh.misc.DisconnectError as e:
            if e.code == asyncssh.DISC_NO_MORE_AUTH_METHODS_AVAILABLE:
                last_error = e
                continue
    else:
        raise last_error

    return conn
示例#25
0
 async def connect(self, timeout=None):
     try:
         self.conn, self.client = await asyncio.wait_for(
             asyncssh.create_connection(MySSHClient,
                                        self.hostname,
                                        username=self.username,
                                        known_hosts=None),
             timeout=timeout)
         return True
     except (OSError, asyncssh.Error, asyncio.TimeoutError):
         # await self.node.feedback('ssh_status', 'connect failed')
         # print('SshProxy.connect failed: {}'.format(e))
         self.conn, self.client = None, None
         return False
     except ValueError as exc:
         # seen raised by asyncssh for some reason,
         # anyway bottom line is we can't connect
         #
         self.conn, self.client = None, None
         return False
示例#26
0
    def _ssh_runner(self, connection, task, killers, command, streams):
        if streams and streams['stdin'].channel._session:
            stdin, stdout, stderr, conn = streams['stdin'], streams['stdout'], streams['stderr'], streams['connection']
            log.debug('Reuse ssh connection')
        else:
            try:
                ip, port = parse_host(connection['ip'], 22)
                conn, client = yield from asyncssh.create_connection(None, host=ip,
                                                                     port=port,
                                                                     username=connection.get('login'),
                                                                     password=connection.get('password'),
                                                                     server_host_keys=None)
                stdin, stdout, stderr = yield from conn.open_session(term_type='xterm-color', term_size=(80, 24))
            except asyncio.CancelledError:
                log.error("Cannot open SSH-session", exc_info=False)
                self.db_log.error("Не удалось открыть ssh соединение", str(ex), 'connection', connection['_id'])
                return -999, "", {}
            except Exception as ex:
                log.error("Cannot open SSH-session", exc_info=True)
                self.db_log.error("Не удалось открыть ssh соединение", str(ex), 'connection', connection['_id'])
                return -999, "", {}

            streams = dict(stdin=stdin, stdout=stdout, stderr=stderr, connection=conn)
            log.debug('Open new ssh connectionm host={}'.format(connection.get('ip')))
            killers.append(conn.close)

        try:
            stdin.write("{}\r".format(command))
            results = yield from self._read_ssh_with_ttl(stdout)
        except:
            log.error("Cannot communicate with SSH-session", exc_info=True)
            return -999, "", {}

        log.debug('Run ssh command "{}", output:\n--\n{}--'.format(command, results))

        return 0, results, streams
def run_client():
    global conn

    conn, client = yield from asyncssh.create_connection(None, 'localhost')
    listener = yield from conn.create_server(connection_requested, '', 8080)
    yield from listener.wait_closed()
def run_client():
    conn, client = yield from asyncssh.create_connection(None, 'localhost')
    server = yield from conn.start_server(connection_requested, '', 8888,
                                          encoding='utf-8')
    yield from server.wait_closed()
def run_client():
    conn, client = yield from asyncssh.create_connection(None, 'localhost')
    listener = yield from conn.forward_remote_port('', 8080, 'localhost', 80)
    yield from listener.wait_closed()
示例#30
0
async def create(cmd, host, task=None):
    host.log.debug5(cmd)
    loop = host.loop

    start = time.time()

    if not cmd[0].startswith('ssh') or nuka.cli.args.ssh:
        def protocol_factory():
            return subprocess.SubprocessStreamProtocol(
                loop=loop, limit=DEFAULT_LIMIT)

        await host.acquire_session_slot()
        transport, protocol = await loop.subprocess_exec(
            protocol_factory,
            *cmd,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            preexec_fn=os.setpgrp,
            close_fds=True)

        proc = Process(transport, protocol, host, task, cmd, start)
    else:
        def protocol_factory():
            return SSHClientProcess(host, task, cmd, start)

        # retrieve params from ssh command
        tmp_cmd = cmd[:]
        ssh_cmd = tmp_cmd.pop()
        hostname = tmp_cmd.pop()
        agent_forwarding = False
        known_hosts = ()
        attempts = 1
        timeout = 924  # Default TCP Timeout on debian
        while tmp_cmd:
            v = tmp_cmd.pop(0)
            if v == '-l':
                username = tmp_cmd.pop(0)
            elif v == '-p':
                port = tmp_cmd.pop(0)
            elif v in ('-A', '-oForwardAgent=yes'):
                agent_forwarding = True
            elif v == '-oStrictHostKeyChecking=no':
                known_hosts = None
            elif v.startswith('-oConnectionAttempts'):
                attempts = int(v.split('=', 1)[1].strip())
            elif v.startswith('-oConnectTimeout'):
                timeout = int(v.split('=', 1)[1].strip())

        if known_hosts is not None:
            filename = os.path.expanduser('~/.ssh/known_hosts')
            if os.path.isfile(filename):
                try:
                    known_hosts = get_known_hosts(filename)
                except ValueError as e:
                    host.fail(e)
                    msg = ' '.join(e.args)
                    nuka.run_vars['exit_message'] = 'FATAL: ' + msg
                    return

        uid = (username, host)
        conn = asyncssh_connections.get(uid, {}).get('conn')
        if conn is None:
            exc = None
            client_keys = await get_keys(loop)
            asyncssh_connections_tasks[uid] = loop.create_task(
                delay_connection(uid, loop)
            )
            try:
                await asyncssh_connections_tasks[uid]
            except asyncio.CancelledError as e:
                exc = LookupError(OSError('sigint'), host)
                host.fail(exc)
                return

            for i in range(1, attempts + 1):
                host.log.debug5('open connection {0}/{1} at {2}'.format(
                                i, attempts, time.time()))
                try:
                    if nuka.run_vars['sigint']:
                        exc = LookupError(OSError('sigint'), host)
                        break
                    asyncssh_connections_tasks[uid] = loop.create_task(
                        asyncssh.create_connection(
                            lambda: SSHClient(uid),
                            hostname, int(port),
                            username=username,
                            known_hosts=known_hosts,
                            agent_forwarding=agent_forwarding,
                            client_keys=client_keys,
                            loop=loop,
                            )
                        )
                    conn, client = await asyncio.wait_for(
                            asyncssh_connections_tasks[uid],
                            timeout=timeout, loop=loop)
                    break
                except asyncio.CancelledError as e:
                    exc = LookupError(OSError('sigint'), host)
                    break
                except asyncio.TimeoutError as e:
                    timeouts = asyncssh_connections[uid]['timeouts']
                    asyncssh_connections[uid]['timeouts'] = timeouts + 1
                    if i == attempts:
                        host.log.error('TimeoutError({0}) exceeded '.format(
                            timeout, i, attempts))
                        exc = LookupError(e, host)
                    else:
                        asyncssh_connections_tasks[uid] = loop.create_task(
                            asyncio.sleep(1 + random.random(), loop=loop)
                        )
                        try:
                            await asyncssh_connections_tasks[uid]
                        except asyncio.CancelledError as e:
                            exc = LookupError(e, host)
                            break
                except (OSError, socket.error) as e:
                    exc = LookupError(e, host)
                    break

            if exc is not None:
                host.fail(exc)
                raise exc

            asyncssh_connections[uid]['conn'] = conn
        await host.acquire_session_slot()
        chan, proc = await conn.create_session(
                protocol_factory, ssh_cmd, encoding=None)
        await proc.redirect(asyncssh.PIPE, asyncssh.PIPE, asyncssh.PIPE,
                            DEFAULT_LIMIT)
    host._processes[id(proc)] = proc
    loop.create_task(proc.exit())

    return proc
def run_client():
    conn, client = yield from asyncssh.create_connection(None, 'localhost')
    listener = yield from conn.forward_local_port('', 0, 'www.google.com', 80)
    print('Listening on port %s...' % listener.get_port())
    yield from listener.wait_closed()
示例#32
0
def run_client():
    conn, client = yield from asyncssh.create_connection(None, 'localhost')
    chan, session = yield from conn.create_session(MySSHClientSession, 'bc')
    yield from chan.wait_closed()
    conn.close()