How to use the asyncssh.connect function in asyncssh

To help you get started, we’ve selected a few asyncssh examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ronf / asyncssh / tests / test_connection_auth.py View on Github external
async def connect():
            """Connect to the server using options"""

            async with asyncssh.connect(self._server_addr, self._server_port,
                                        options=options):
                pass
github PyPlanet / PyPlanet / pyplanet / core / storage / drivers / asyncssh / __init__.py View on Github external
async 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__()
github selfuryon / netdev / netdev / vendors / mikrotik / mikrotik_routeros.py View on Github external
async 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
github ronf / asyncssh / examples / stream_direct_client.py View on Github external
async def run_client():
    async with asyncssh.connect('localhost') as conn:
        reader, writer = await 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 = await reader.read()
        sys.stdout.buffer.write(response)
github ronf / asyncssh / examples / listening_client.py View on Github external
async def run_client():
    async with asyncssh.connect('localhost') as conn:
        server = await conn.create_server(connection_requested, '', 8888,
                                          encoding='utf-8')

        if server:
            await server.wait_closed()
        else:
            print('Listener couldn''t be opened.', file=sys.stderr)
github Snawoot / rsp / rsp / ssh_pool.py View on Github external
async 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():
github radiasoft / sirepo / sirepo / job_driver / sbatch.py View on Github external
async def _agent_start(self, msg):
        self._agent_starting = True
        try:
            async with asyncssh.connect(
                cfg.host,
    #TODO(robnagler) add password management
                username=msg.username,
                password=msg.password + msg.otp if 'nersc' in cfg.host else msg.password,
                known_hosts=_KNOWN_HOSTS,
            ) as c:
                script = f'''#!/bin/bash
{self._agent_start_dev()}
set -e
mkdir -p '{self._srdb_root}'
cd '{self._srdb_root}'
{self._agent_env()}
setsid {cfg.sirepo_cmd} job_agent >& job_agent.log &
disown
'''
                async with c.create_process('/bin/bash') as p:
github selfuryon / netdev / netdev / connections / ssh.py View on Github external
async def connect(self) -> None:
        """ Etablish the SSH connection """
        self._logger.info(
            "Host %s: Establishing SSH connection on port %s", self._host, self._port
        )
        try:
            self._conn = await asyncssh.connect(
                self._host,
                self._port,
                loop=self._loop,
                tunnel=self._tunnel,
                **self._conn_dict,
            )
        except asyncssh.DisconnectError as error:
            raise DisconnectError(self._host, error.code, error.reason)

        await self._start_session()
github selfuryon / netdev / netdev / vendors / base.py View on Github external
async 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))
github ronf / asyncssh / examples / set_environment.py View on Github external
async def run_client():
    async with asyncssh.connect('localhost') as conn:
        result = await conn.run('env', env={'LANG': 'en_GB',
                                            'LC_COLLATE': 'C'})
        print(result.stdout, end='')