本文整理汇总了Python中paramiko.client方法的典型用法代码示例。如果您正苦于以下问题:Python paramiko.client方法的具体用法?Python paramiko.client怎么用?Python paramiko.client使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类paramiko
的用法示例。
在下文中一共展示了paramiko.client方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_missing_host_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [as 别名]
def test_missing_host_key(self):
client = paramiko.SSHClient()
file1 = make_tests_data_path('known_hosts_example')
file2 = make_tests_data_path('known_hosts_example2')
filename = make_tests_data_path('known_hosts')
copyfile(file1, filename)
client.load_host_keys(filename)
n1 = len(client._host_keys)
autoadd = AutoAddPolicy()
entry = paramiko.hostkeys.HostKeys(file2)._entries[0]
hostname = entry.hostnames[0]
key = entry.key
autoadd.missing_host_key(client, hostname, key)
self.assertEqual(len(client._host_keys), n1 + 1)
self.assertEqual(paramiko.hostkeys.HostKeys(filename),
client._host_keys)
os.unlink(filename)
示例2: __init__
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [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
示例3: run
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [as 别名]
def run(self, argv):
try:
self._connect()
cmd = " ".join(self.escape(s) for s in argv)
stdin, stdout, stderr = self.client.exec_command(cmd)
status, stdout_chunks, stderr_chunks = self._read_results(stdin, stdout, stderr)
out = b''.join(stdout_chunks)
error = b''.join(stderr_chunks)
if status != 0:
err("Command %s failed with status %d on host %s" % (cmd, status, self.hostname))
else:
debug("Command %s succeeded on host %s, output was %s and %s" %
(cmd, self.hostname, str(out, 'utf-8'), str(error, 'utf-8')))
return ExecutionResult(cmd, status, str(out, 'utf-8'), str(error, 'utf-8'))
except (ConnectionResetError, paramiko.ssh_exception.SSHException):
self.client = None
raise BadSSHHost("SSH connection to host %s was reset" % (self.hostname,))
示例4: get_policy_class
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [as 别名]
def get_policy_class(policy):
origin_policy = policy
policy = policy.lower()
if not policy.endswith('policy'):
policy += 'policy'
dic = {k.lower(): v for k, v in vars(paramiko.client).items() if type(v)
is type and issubclass(v, paramiko.client.MissingHostKeyPolicy)}
try:
cls = dic[policy]
except KeyError:
raise ValueError('Unknown policy {!r}'.format(origin_policy))
return cls
示例5: get_application_settings
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [as 别名]
def get_application_settings():
base_dir = os.path.dirname(__file__)
filename = os.path.join(base_dir, 'known_hosts')
host_keys = get_host_keys(filename)
system_host_keys = get_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
policy_class = get_policy_class(options.policy)
logging.info(policy_class.__name__)
if policy_class is paramiko.client.AutoAddPolicy:
host_keys.save(filename) # for permission test
host_keys._last_len = len(host_keys)
tornado.ioloop.PeriodicCallback(
lambda: save_host_keys(host_keys, filename),
options.period * 1000 # milliseconds
).start()
elif policy_class is paramiko.client.RejectPolicy:
if not host_keys and not system_host_keys:
raise ValueError('Empty known_hosts with reject policy?')
settings = dict(
template_path=os.path.join(base_dir, 'templates'),
static_path=os.path.join(base_dir, 'static'),
cookie_secret=uuid.uuid4().hex,
xsrf_cookies=False, ##修改源代码的地方
host_keys=host_keys,
system_host_keys=system_host_keys,
policy=policy_class(),
debug=options.debug
)
return settings
示例6: test_is_missing_host_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [as 别名]
def test_is_missing_host_key(self):
client = paramiko.SSHClient()
file1 = make_tests_data_path('known_hosts_example')
file2 = make_tests_data_path('known_hosts_example2')
client.load_host_keys(file1)
client.load_system_host_keys(file2)
autoadd = AutoAddPolicy()
for f in [file1, file2]:
entry = paramiko.hostkeys.HostKeys(f)._entries[0]
hostname = entry.hostnames[0]
key = entry.key
self.assertIsNone(
autoadd.is_missing_host_key(client, hostname, key)
)
for f in [file1, file2]:
entry = paramiko.hostkeys.HostKeys(f)._entries[0]
hostname = entry.hostnames[0]
key = entry.key
key.get_name = lambda: 'unknown'
self.assertTrue(
autoadd.is_missing_host_key(client, hostname, key)
)
del key.get_name
for f in [file1, file2]:
entry = paramiko.hostkeys.HostKeys(f)._entries[0]
hostname = entry.hostnames[0][1:]
key = entry.key
self.assertTrue(
autoadd.is_missing_host_key(client, hostname, key)
)
file3 = make_tests_data_path('known_hosts_example3')
entry = paramiko.hostkeys.HostKeys(file3)._entries[0]
hostname = entry.hostnames[0]
key = entry.key
with self.assertRaises(paramiko.BadHostKeyException):
autoadd.is_missing_host_key(client, hostname, key)
示例7: get_policy_dictionary
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [as 别名]
def get_policy_dictionary():
dic = {
k.lower(): v for k, v in vars(paramiko.client).items() if type(v)
is type and issubclass(v, paramiko.client.MissingHostKeyPolicy)
and v is not paramiko.client.MissingHostKeyPolicy
}
return dic
示例8: check_policy_setting
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [as 别名]
def check_policy_setting(policy_class, host_keys_settings):
host_keys = host_keys_settings['host_keys']
host_keys_filename = host_keys_settings['host_keys_filename']
system_host_keys = host_keys_settings['system_host_keys']
if policy_class is paramiko.client.AutoAddPolicy:
host_keys.save(host_keys_filename) # for permission test
elif policy_class is paramiko.client.RejectPolicy:
if not host_keys and not system_host_keys:
raise ValueError(
'Reject policy could not be used without host keys.'
)
示例9: is_missing_host_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [as 别名]
def is_missing_host_key(self, client, hostname, key):
k = client._system_host_keys.lookup(hostname) or \
client._host_keys.lookup(hostname)
if k is None:
return True
host_key = k.get(key.get_name(), None)
if host_key is None:
return True
if host_key != key:
raise paramiko.BadHostKeyException(hostname, key, host_key)
示例10: sqs_delete_queue
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [as 别名]
def sqs_delete_queue(queue_url, client=None):
"""This deletes an SQS queue given its URL
Parameters
----------
queue_url : str
The SQS URL of the queue to delete.
client : boto3.Client or None
If None, this function will instantiate a new `boto3.Client` object to
use in its operations. Alternatively, pass in an existing `boto3.Client`
instance to re-use it here.
Returns
-------
bool
True if the queue was deleted successfully. False otherwise.
"""
if not client:
client = boto3.client('sqs')
try:
client.delete_queue(QueueUrl=queue_url)
return True
except Exception:
LOGEXCEPTION('could not delete the specified queue: %s'
% (queue_url,))
return False
示例11: delete_spot_fleet_cluster
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [as 别名]
def delete_spot_fleet_cluster(
spot_fleet_reqid,
client=None,
):
"""
This deletes a spot-fleet cluster.
Parameters
----------
spot_fleet_reqid : str
The fleet request ID returned by `make_spot_fleet_cluster`.
client : boto3.Client or None
If None, this function will instantiate a new `boto3.Client` object to
use in its operations. Alternatively, pass in an existing `boto3.Client`
instance to re-use it here.
Returns
-------
Nothing.
"""
if not client:
client = boto3.client('ec2')
resp = client.cancel_spot_fleet_requests(
SpotFleetRequestIds=[spot_fleet_reqid],
TerminateInstances=True
)
return resp
示例12: _get_cli
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [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")
示例13: __init__
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [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)
示例14: _connect_in_background
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [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
示例15: __init__
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import client [as 别名]
def __init__(self, hostname, ssh_username=None, ssh_password=None, ssh_identity_file=None):
if hasattr(hostname, "ip"):
self.hostname = hostname.ip
else:
self.hostname = hostname
if not self.hostname:
raise NoHostsSpecified("No SSH host specified")
self.ssh_username = ssh_username
self.ssh_password = ssh_password
self.ssh_identity_file = ssh_identity_file
self.client = None