当前位置: 首页>>代码示例>>Python>>正文


Python asyncssh.connect方法代码示例

本文整理汇总了Python中asyncssh.connect方法的典型用法代码示例。如果您正苦于以下问题:Python asyncssh.connect方法的具体用法?Python asyncssh.connect怎么用?Python asyncssh.connect使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在asyncssh的用法示例。


在下文中一共展示了asyncssh.connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: connect

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def connect(self):
        """
        Basic asynchronous connection method

        It connects to device and makes some preparation steps for working.
        Usual using 3 functions:

        * _establish_connection() for connecting to device
        * _set_base_prompt() for finding and setting device prompt
        * _disable_paging() for non interactive output in commands
        """
        logger.info("Host {}: Trying to connect to the device".format(self._host))
        await self._establish_connection()
        await self._set_base_prompt()
        await self._disable_paging()
        logger.info("Host {}: Has connected to the device".format(self._host)) 
开发者ID:selfuryon,项目名称:netdev,代码行数:18,代码来源:base.py

示例2: _establish_connection

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def _establish_connection(self):
        """Establish SSH connection to the network device"""
        logger.info(
            "Host {}: Establishing connection to port {}".format(self._host, self._port)
        )
        output = ""
        # initiate SSH connection
        fut = asyncssh.connect(**self._connect_params_dict)
        try:
            self._conn = await asyncio.wait_for(fut, self._timeout)
        except asyncssh.DisconnectError as e:
            raise DisconnectError(self._host, e.code, e.reason)
        except asyncio.TimeoutError:
            raise TimeoutError(self._host)
        self._stdin, self._stdout, self._stderr = await self._conn.open_session(
            term_type="Dumb"
        )
        logger.info("Host {}: Connection is established".format(self._host))
        # Flush unnecessary data
        output = await self._read_until_prompt()
        logger.debug(
            "Host {}: Establish Connection Output: {}".format(self._host, repr(output))
        )
        return output 
开发者ID:selfuryon,项目名称:netdev,代码行数:26,代码来源:mikrotik_routeros.py

示例3: prepare_ciphers_and_headers

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def prepare_ciphers_and_headers(self, reader_remote, writer_remote, host, port, handler):
        if not self.direct:
            reader_remote, writer_remote = proto.sslwrap(reader_remote, writer_remote, self.sslclient, False, self.host_name)
            if not handler or not handler.ready:
                _, writer_cipher_r = await prepare_ciphers(self.cipher, reader_remote, writer_remote, self.bind)
            else:
                writer_cipher_r = None
            whost, wport = (host, port) if self.relay.direct else (self.relay.host_name, self.relay.port)
            if self.rproto.reuse():
                if not self.streams.done():
                    self.streams.set_result((reader_remote, writer_remote))
                reader_remote, writer_remote = handler.connect(whost, wport)
            elif self.ssh:
                reader_remote, writer_remote = await reader_remote.open_connection(whost, wport)
            else:
                await self.rproto.connect(reader_remote=reader_remote, writer_remote=writer_remote, rauth=self.auth, host_name=whost, port=wport, writer_cipher_r=writer_cipher_r, myhost=self.host_name, sock=writer_remote.get_extra_info('socket'))
            return await self.relay.prepare_ciphers_and_headers(reader_remote, writer_remote, host, port, handler)
        return reader_remote, writer_remote 
开发者ID:qwj,项目名称:python-proxy,代码行数:20,代码来源:server.py

示例4: test_basic_login

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def test_basic_login(self):

    async def run_client():
      async with asyncssh.connect(
          'localhost',
          port=8888,
          username='johnny',
          password='secretpw',
          known_hosts=None) as _:
        pass

    ssh_key_file = 'ssh.key'
    SSH.generate_ssh_key(ssh_key_file)

    options = {'enabled': 'True', 'port': 8888}
    server_coro = asyncssh.create_server(
        lambda: SSH(options, self.loop),
        '0.0.0.0',
        8888,
        server_host_keys=['ssh.key'])
    self.server = self.loop.run_until_complete(server_coro)

    try:
      self.loop.run_until_complete(run_client())
    except asyncssh.misc.PermissionDenied:
      pass 
开发者ID:johnnykv,项目名称:heralding,代码行数:28,代码来源:test_ssh.py

示例5: __aenter__

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def __aenter__(self):
        """Async Context Manager"""
        await self.connect()
        return self 
开发者ID:selfuryon,项目名称:netdev,代码行数:6,代码来源:base.py

示例6: _establish_connection

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def _establish_connection(self):
        """Establishing SSH connection to the network device"""
        logger.info(
            "Host {}: Establishing connection to port {}".format(self._host, self._port)
        )
        output = ""
        # initiate SSH connection
        fut = asyncssh.connect(**self._connect_params_dict)
        try:
            self._conn = await asyncio.wait_for(fut, self._timeout)
        except asyncssh.DisconnectError as e:
            raise DisconnectError(self._host, e.code, e.reason)
        except asyncio.TimeoutError:
            raise TimeoutError(self._host)
        self._stdin, self._stdout, self._stderr = await self._conn.open_session(
            term_type="Dumb", term_size=(200, 24)
        )
        logger.info("Host {}: Connection is established".format(self._host))
        # Flush unnecessary data
        delimiters = map(re.escape, type(self)._delimiter_list)
        delimiters = r"|".join(delimiters)
        output = await self._read_until_pattern(delimiters)
        logger.debug(
            "Host {}: Establish Connection Output: {}".format(self._host, repr(output))
        )
        return output 
开发者ID:selfuryon,项目名称:netdev,代码行数:28,代码来源:base.py

示例7: connect

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def connect(self):
        """
        Async Connection method

        RouterOS using 2 functions:

        * _establish_connection() for connecting to device
        * _set_base_prompt() for finding and setting device prompt
        """
        logger.info("Host {}: Connecting to device".format(self._host))
        await self._establish_connection()
        await self._set_base_prompt()
        logger.info("Host {}: Connected to device".format(self._host)) 
开发者ID:selfuryon,项目名称:netdev,代码行数:15,代码来源:mikrotik_routeros.py

示例8: create

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def create(hub, name: str, target: Dict[str, Any]):
    '''
    Create a connection to the remote system using a dict of values that map
    to this plugin. Name the connection for future use, the connection data
    will be stored on the hub under hub.tunnel.asyncssh.CONS
    :param name:
    :param target:
    '''
    # The id MUST be in the target, everything else might be in the target, conf, or elsewhere
    id_ = target.get('host', target.get('id'))

    possible_options = set(inspect.getfullargspec(asyncssh.SSHClientConnectionOptions.prepare).args)
    # Remove options from `inspect` that don't belong
    possible_options -= {'self', 'args', 'kwargs'}
    # Add connection options that aren't specified in `SSHClientConnectionOptions.prepare`
    possible_options.update({'port', 'loop', 'tunnel', 'family', 'flags', 'local_addr', 'options'})
    # Check for each possible SSHClientConnectionOption in the target, config, then autodetect (if necessary)
    con_opts = {'known_hosts': None}
    for arg in possible_options:
        opt = _get_asyncssh_opt(hub, target, arg)
        if opt is not None:
            con_opts[arg] = opt

    try:
        conn = await asyncssh.connect(id_, **con_opts)
    except Exception:
        log.error(f'Failed to connect to {id_}')
        return False
    sftp = await conn.start_sftp_client()
    hub.tunnel.asyncssh.CONS[name] = {
        'con': conn,
        'sftp': sftp,
        'sudo': target.get('sudo', None)}
    return True 
开发者ID:saltstack,项目名称:heist,代码行数:36,代码来源:asyncssh_tunnel.py

示例9: _build_conn

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def _build_conn(self):
        async def fail():
            self._logger.debug("Failed upstream connection. Backoff for %d "
                               "seconds", self._backoff)
            await asyncio.sleep(self._backoff)

        while True:
            try:
                async with self._ratelimit:
                    self._logger.debug("_build_conn: connect attempt.")
                    conn = await asyncio.wait_for(
                        asyncssh.connect(self._dst_address,
                                         self._dst_port,
                                         options=self._ssh_options()),
                        self._timeout)
                    break
            except asyncio.TimeoutError:
                self._logger.error("Connection to upstream timed out.")
                await fail()
            except asyncio.CancelledError:
                raise
            except Exception as exc:
                self._logger.exception("Got exception while connecting to upstream: %s", str(exc))
                await fail()
        self._logger.debug("Successfully built upstream connection.")
        while self._waiters:
            fut = self._waiters.popleft()
            if not fut.cancelled():
                self._logger.warning("Pool exhausted. Dispatching connection directly to waiter!")
                fut.set_result(conn)
                break
        else:
            self._reserve.append(conn) 
开发者ID:Snawoot,项目名称:rsp,代码行数:35,代码来源:ssh_pool.py

示例10: run_client

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def run_client(host, command):
#   async with asyncssh.connect(host, username='username', password='password') as conn:
    async with asyncssh.connect(host, username='username') as conn:
        return await conn.run(command) 
开发者ID:DedSecInside,项目名称:Awesome-Scripts,代码行数:6,代码来源:async_shutdown.py

示例11: async_run_command

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def async_run_command(self, command, retry=False):
        """Run commands through an SSH connection.

        Connect to the SSH server if not currently connected, otherwise
        use the existing connection.
        """
        if self._client is None and not retry:
            await self.async_connect()
            return await self.async_run_command(command, retry=True)
        else:
            if self._client is not None:
                try:
                    result = await asyncio.wait_for(self._client.run(
                        "%s && %s" % (_PATH_EXPORT_COMMAND, command)), 9)
                except asyncssh.misc.ChannelOpenError:
                    if not retry:
                        await self.async_connect()
                        return await self.async_run_command(
                            command, retry=True)
                    else:
                        _LOGGER.error("Cant connect to host, giving up!")
                        return []
                except TimeoutError:
                    self._client = None
                    _LOGGER.error("Host timeout.")
                    return []

                return result.stdout.split('\n')

            else:
                _LOGGER.error("Cant connect to host, giving up!")
                return [] 
开发者ID:kennedyshead,项目名称:aioasuswrt,代码行数:34,代码来源:connection.py

示例12: async_connect

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def async_connect(self):
        """Fetches the client or creates a new one."""

        kwargs = {
            'username': self._username if self._username else None,
            'client_keys': [self._ssh_key] if self._ssh_key else None,
            'port': self._port,
            'password': self._password if self._password else None,
            'known_hosts': None,
            'server_host_key_algs': ['ssh-rsa']
        }

        self._client = await asyncssh.connect(self._host, **kwargs) 
开发者ID:kennedyshead,项目名称:aioasuswrt,代码行数:15,代码来源:connection.py

示例13: connect

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def connect(self):
		ssh = await asyncssh.connect(
			host=self.host, port=self.port, known_hosts=self.known_hosts, username=self.username, password=self.password,
			client_keys=self.client_keys, passphrase=self.passphrase,
		).__aenter__()
		await async_generator.yield_(ssh)
		await ssh.__aexit__() 
开发者ID:PyPlanet,项目名称:PyPlanet,代码行数:9,代码来源:__init__.py

示例14: connect_sftp

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def connect_sftp(self):
		"""
		Get sftp client.
		
		:return: Sftp client.
		:rtype: asyncssh.SFTPClient
		"""
		ssh = await self.connect().__aenter__()
		sftp = await ssh.start_sftp_client().__aenter__()
		await async_generator.yield_(sftp)
		await sftp.__aexit__()
		await ssh.__aexit__() 
开发者ID:PyPlanet,项目名称:PyPlanet,代码行数:14,代码来源:__init__.py

示例15: ssh_command

# 需要导入模块: import asyncssh [as 别名]
# 或者: from asyncssh import connect [as 别名]
def ssh_command(func):
    func = click.option(
        "-i", "--identity-file",
        type=click.File(lazy=False),
        default=str(get_private_key_path()),
        help="Path to the private key file",
        show_default=True
    )(func)
    func = click.option(
        "-b", "--batch-size",
        type=int,
        default=20,
        help="By default, command won't connect to all servers "
             "simultaneously, it is trying to process servers in batches. "
             "Negative number or 0 means connect to all hosts",
        show_default=True,
    )(func)

    @functools.wraps(func)
    @click.pass_context
    def decorator(ctx, identity_file, batch_size, *args, **kwargs):
        private_key = asyncssh.import_private_key(identity_file.read())
        batch_size = batch_size if batch_size > 0 else None
        identity_file.close()

        ctx.obj["private_key"] = private_key
        ctx.obj["batch_size"] = batch_size
        ctx.obj["event_loop"] = asyncio.get_event_loop()

        return func(*args, **kwargs)

    return decorator 
开发者ID:Mirantis,项目名称:ceph-lcm,代码行数:34,代码来源:utils.py


注:本文中的asyncssh.connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。