本文整理匯總了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))
示例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
示例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
示例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
示例5: __aenter__
# 需要導入模塊: import asyncssh [as 別名]
# 或者: from asyncssh import connect [as 別名]
def __aenter__(self):
"""Async Context Manager"""
await self.connect()
return self
示例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
示例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))
示例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
示例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)
示例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)
示例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 []
示例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)
示例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__()
示例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__()
示例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