本文整理汇总了Python中paramiko.client.SSHClient方法的典型用法代码示例。如果您正苦于以下问题:Python client.SSHClient方法的具体用法?Python client.SSHClient怎么用?Python client.SSHClient使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类paramiko.client
的用法示例。
在下文中一共展示了client.SSHClient方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from paramiko import client [as 别名]
# 或者: from paramiko.client import SSHClient [as 别名]
def __init__(self,
host: str,
private_host: str,
username: str,
key: str,
config: ConfigParser,
debug: bool,
use_public: bool = True) -> None:
self.host = host
self.private_host = private_host
self.username = username
self.key = key
self.config = config
self.fix_relpaths_in_config()
self.use_public = use_public
self.debug = debug
# Uses only one ssh client per instance object
self._cli: SSHClient = None
示例2: wait_until_accessible
# 需要导入模块: from paramiko import client [as 别名]
# 或者: from paramiko.client import SSHClient [as 别名]
def wait_until_accessible(self) -> None:
"""Waits until the instance is accesible through SSHClient
It attempts `const.RETRIES` time to ping SSH port to See
if it's listening for incoming connections. In each attempt,
it waits `const.RETRY_DELAY`.
Raises
------
ConnectionError
If the instance is unaccesible through SSH
"""
retry_count = 0
while retry_count <= const.RETRIES:
if self.is_up():
logger.debug(f"Instance {self.host} is UP & accessible on port 22")
return
time.sleep(const.RETRY_DELAY)
retry_count += 1
logger.debug(f"Instance {self.host} not accesible. Retrying")
raise ConnectionError(f"{self.host} is unreachable through ssh.")
示例3: ssh_signup
# 需要导入模块: from paramiko import client [as 别名]
# 或者: from paramiko.client import SSHClient [as 别名]
def ssh_signup(user):
# TODO: configure nodes used for authentication
auth_node = next(iter(SSH.AVAILABLE_NODES))
ssh_key = TensorHiveManager().dedicated_ssh_key
test_client = SSHClient()
test_client.load_system_host_keys()
test_client.set_missing_host_key_policy(WarningPolicy())
try:
test_client.connect(auth_node, username=user['username'], pkey=ssh_key)
except AuthenticationException:
return {'msg': G['unpriviliged']}, 403
except (BadHostKeyException, SSHException, socket.error) as e:
return 'An error ocurred while authenticating: {}'.format(e), 500
finally:
test_client.close()
return do_create(user)
示例4: test_remote_shell
# 需要导入模块: from paramiko import client [as 别名]
# 或者: from paramiko.client import SSHClient [as 别名]
def test_remote_shell():
rs = RemoteShell()
assert isinstance(rs.ssh, SSHClient)
示例5: __enter__
# 需要导入模块: from paramiko import client [as 别名]
# 或者: from paramiko.client import SSHClient [as 别名]
def __enter__(self):
self._client = SSHClient()
self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
username = parse('config.ssh.user').find(self._cluster)[0].value
hostname = parse('config.host').find(self._cluster)[0].value
port = parse('config.port').find(self._cluster)
if port:
port = port[0].value
else:
port = 22
passphrase \
= parse('config.ssh.passphrase').find(self._cluster)
if passphrase:
passphrase = passphrase[0].value
else:
passphrase = None
key_name = parse('config.ssh.key').find(self._cluster)[0].value
key_path = os.path.join(cumulus.config.ssh.keyStore,
key_name)
private_key = self._load_rsa_key(key_path, passphrase)
self._client.connect(hostname=hostname, port=port,
username=username, pkey=private_key)
return self
示例6: run_ssh_command
# 需要导入模块: from paramiko import client [as 别名]
# 或者: from paramiko.client import SSHClient [as 别名]
def run_ssh_command(self, command):
key = task_key(self.request.id)
redis.set(key, "")
client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy)
known_hosts = os.path.expanduser('~/.ssh/known_hosts')
try:
client.load_host_keys(known_hosts) # So that we also save back the new host
except FileNotFoundError:
if not os.path.exists(os.path.dirname(known_hosts)):
os.mkdir(os.path.dirname(known_hosts))
open(known_hosts, "w").write("") # so connect doesn't barf when trying to save
if type(command) == list:
commands = command
else:
commands = [command]
for c in commands:
if os.path.exists(keyfile):
pkey = RSAKey.from_private_key_file(keyfile)
else:
pkey = None
client.connect(settings.DOKKU_HOST, port=settings.DOKKU_SSH_PORT, username="dokku", pkey=pkey, allow_agent=False, look_for_keys=False)
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command(c)
while True:
anything = False
while channel.recv_ready():
data = channel.recv(1024)
handle_data(key, data)
anything = True
while channel.recv_stderr_ready():
data = channel.recv_stderr(1024)
handle_data(key, data)
anything = True
if not anything:
if channel.exit_status_ready():
break
time.sleep(0.1)
return redis.get(key).decode("utf-8")
示例7: _get_cli
# 需要导入模块: from paramiko import client [as 别名]
# 或者: from paramiko.client import SSHClient [as 别名]
def _get_cli(self) -> paramiko.SSHClient:
"""Get an `SSHClient` in order to execute commands.
This will cache an existing SSHClient to optimize resource.
This is a private method and should only be used in this module.
Returns
-------
paramiko.SSHClient
The client for latter use.
Raises
------
SSHConnectingError
In case opening an SSH connection fails.
"""
try:
if (self._cli is None or self._cli.get_transport() is None or
not self._cli.get_transport().is_active()):
# Set cli in case it was not set or if it was closed
cli = paramiko.SSHClient()
cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
hostname = self.host if self.use_public else self.private_host
cli.connect(hostname=hostname,
username=self.username, key_filename=self.key,
allow_agent=False, look_for_keys=False)
self._cli = cli
return self._cli
except paramiko.ssh_exception.SSHException:
raise errors.SSHConnectingError(f"Error opening SSH connection with {hostname}. "
"Double check information provided in the secrets file")
示例8: __init__
# 需要导入模块: from paramiko import client [as 别名]
# 或者: from paramiko.client import SSHClient [as 别名]
def __init__(self, host, user, password, cwd, mp_executable, api_stubs_path):
from paramiko.client import SSHClient
self._host = host
self._user = user
self._password = password
self._sftp = None
self._client = SSHClient()
self._client.load_system_host_keys()
# TODO: does it get closed properly after process gets killed?
self._client.connect(hostname=host, username=user, password=password)
self._cwd = cwd
super().__init__(mp_executable, api_stubs_path, cwd=cwd)
示例9: _connect_in_background
# 需要导入模块: from paramiko import client [as 别名]
# 或者: from paramiko.client import SSHClient [as 别名]
def _connect_in_background(self, cmd_line_str):
try:
from paramiko.client import SSHClient
except ImportError:
self._show_error(
"SSH connection requires an extra package -- 'paramiko'.\n"
+ "You can install it via 'Tools => Manage plug-ins' or via system package manager."
)
return
self._client = SSHClient()
self._client.load_system_host_keys()
self._client.connect(hostname=self._host, username=self._user, password=self._password)
self._check_install_thonny_backend()
env = {
"THONNY_USER_DIR": "~/.config/Thonny",
"THONNY_FRONTEND_SYS_PATH": "[]",
}
stdin, stdout, stderr = self._client.exec_command(
cmd_line_str, bufsize=0, timeout=None, get_pty=False, environment=env
)
self._proc = SshPopen(stdin, stdout, stderr)
# setup asynchronous output listeners
Thread(target=self._listen_stdout, args=(stdout,), daemon=True).start()
Thread(target=self._listen_stderr, args=(stderr,), daemon=True).start()
self._send_msg(ToplevelCommand("get_environment_info"))
self._starting = False
示例10: _remote_script
# 需要导入模块: from paramiko import client [as 别名]
# 或者: from paramiko.client import SSHClient [as 别名]
def _remote_script(self, host_fname: str, desc: str) -> Generator[str, None, None]:
"""Sends a local file containing a script to the instance
using Paramiko SFTP.
It should be used as a context manager for latter execution of
the script. See `_run_script` on how to use it.
After the context manager exists, then the file is removed from
the instance.
This is a private method and should only be used in this module.
Parameters
----------
host_fname : str
The local script filename
desc : str
A description for the script purpose. This will be used
for the copied filename
Yields
-------
str
The remote filename of the copied local file.
Raises
------
RemoteCommandError
In case sending the script fails.
"""
random_fname = f"{desc}_{uuid.uuid4().hex}.sh"
cli = paramiko.SSHClient()
cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
cli.connect(hostname=self.host, username=self.username,
key_filename=self.key)
sftp = cli.open_sftp()
try:
random_fname = f"{desc}_{uuid.uuid4().hex}.sh"
sftp.put(host_fname, random_fname)
cmd = self._run_cmd(f"chmod +x {random_fname}")
if cmd.success:
yield random_fname
else:
raise errors.RemoteCommandError(f"Error sending local script. {cmd.msg}")
finally:
sftp.remove(random_fname)
sftp.close()
cli.close()