本文整理汇总了Python中paramiko.SSHException方法的典型用法代码示例。如果您正苦于以下问题:Python paramiko.SSHException方法的具体用法?Python paramiko.SSHException怎么用?Python paramiko.SSHException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类paramiko
的用法示例。
在下文中一共展示了paramiko.SSHException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fetch_remote_crashes
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def fetch_remote_crashes(self):
"""
some exception handling code is taken from https://www.programcreek.com/python/example/105570/scp.SCPClient
"""
try:
ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect(hostname=config.remote_system_ip)
self.copy_crashes_dir_with_scp(ssh)
except AuthenticationException:
print("Authentication failed, please verify your credentials: %s")
except SSHException as sshException:
print("Unable to establish SSH connection: %s" % sshException)
except BadHostKeyException as badHostKeyException:
print("Unable to verify server's host key: %s" % badHostKeyException)
finally:
ssh.close()
示例2: connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def connect(self):
"""Call to set connection with remote client."""
try:
self.paramiko_session = paramiko.SSHClient()
self.paramiko_session.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
self.paramiko_session.connect(
self.client.ip, username=self.client.user,
password=self.client.pass_, key_filename=self.client.key,
allow_agent=True, compress=self.client.compress)
except (paramiko.AuthenticationException,
paramiko.ssh_exception.NoValidConnectionsError) as e:
self.logger.error(e)
sys.exit(colored("> {}".format(e), 'red'))
except paramiko.SSHException as e:
self.logger.error(e)
sys.exit(colored("> {}".format(e), 'red'))
self.transfer = network.Network(
self.paramiko_session, self.client.ip, self.client.port)
self.transfer.open()
示例3: sshInstall
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def sshInstall(retry,hostname):
global user
global password
global userInsightfinder
global licenseKey
global samplingInterval
global reportingInterval
global agentType
if retry == 0:
print "Install Fail in", hostname
q.task_done()
return
print "Start installing agent in", hostname, "..."
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if os.path.isfile(password) == True:
s.connect(hostname, username=user, key_filename = password, timeout=60)
else:
s.connect(hostname, username=user, password = password, timeout=60)
transport = s.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
session.exec_command("sudo rm -rf insightagent* InsightAgent* \n \
wget --no-check-certificate https://github.com/insightfinder/InsightAgent/archive/master.tar.gz -O insightagent.tar.gz && \
tar xzvf insightagent.tar.gz && \
cd InsightAgent-master && deployment/checkpackages.sh -env\n")
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
stdin.write(password+'\n')
stdin.flush()
session.recv_exit_status() #wait for exec_command to finish
s.close()
print "Install Succeed in", hostname
q.task_done()
return
except paramiko.SSHException, e:
print "Invalid Username/Password for %s:"%hostname , e
return sshInstall(retry-1,hostname)
示例4: sshStopCron
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def sshStopCron(retry,hostname):
global user
global password
if retry == 0:
print "Stop Cron Failed in", hostname
q.task_done()
return
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if os.path.isfile(password) == True:
s.connect(hostname, username=user, key_filename = password, timeout=60)
else:
s.connect(hostname, username=user, password = password, timeout=60)
transport = s.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
command = "sudo mv /etc/cron.d/ifagent InsightAgent-master/ifagent."+time.strftime("%Y%m%d%H%M%S")+"\n"
session.exec_command(command)
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
stdin.write(password+'\n')
stdin.flush()
session.recv_exit_status() #wait for exec_command to finish
s.close()
print "Stopped Cron in ", hostname
q.task_done()
return
except paramiko.SSHException, e:
print "Invalid Username/Password for %s:"%hostname , e
return sshStopCron(retry-1,hostname)
示例5: sshStopCron
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def sshStopCron(retry,hostname):
global user
global password
if retry == 0:
print "Stop Cron Failed in", hostname
q.task_done()
return
try:
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if os.path.isfile(password) == True:
s.connect(hostname, username=user, key_filename = password, timeout=60)
else:
s.connect(hostname, username=user, password = password, timeout=60)
transport = s.get_transport()
session = transport.open_session()
session.set_combine_stderr(True)
session.get_pty()
command = "./InsightAgent-master/hypervisor/stopcron.sh -t hypervisor\n"
session.exec_command(command)
stdin = session.makefile('wb', -1)
stdout = session.makefile('rb', -1)
stdin.write(password+'\n')
stdin.flush()
session.recv_exit_status() #wait for exec_command to finish
s.close()
print "Stopped Cron in ", hostname
q.task_done()
return
except paramiko.SSHException, e:
print "Invalid Username/Password for %s:"%hostname , e
return sshStopCron(retry-1,hostname)
示例6: test_connectivity
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def test_connectivity(self, time_out=None):
""" Tests if the SSH is active
Arguments:
- time_out: Timeout to connect.
Returns: True if the connection is established or False otherwise
Raises:
Exception
"""
try:
client, proxy = self.connect(time_out)
client.close()
if proxy:
proxy.close()
return True
except paramiko.AuthenticationException:
raise AuthenticationException("Authentication Error!!")
except paramiko.SSHException as e:
if str(e) == "No authentication methods available":
raise AuthenticationException("Authentication Error!!")
return False
except Exception:
return False
示例7: test_fail_percent
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def test_fail_percent(self):
inventory = make_inventory((
'somehost',
('thinghost', {'ssh_hostname': SSHException}),
'anotherhost',
))
state = State(inventory, Config(FAIL_PERCENT=1))
# Ensure we would fail at this point
with self.assertRaises(PyinfraError) as context:
connect_all(state)
assert context.exception.args[0] == 'Over 1% of hosts failed (33%)'
# Ensure the other two did connect
assert len(state.active_hosts) == 2
示例8: get_private_keys
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def get_private_keys():
"""Find SSH keys in standard folder."""
key_formats = [RSAKey, ECDSAKey, Ed25519Key]
ssh_folder = os.path.expanduser("~/.ssh")
available_private_keys = []
if os.path.isdir(ssh_folder):
for key in os.listdir(ssh_folder):
for key_format in key_formats:
try:
parsed_key = key_format.from_private_key_file(
os.path.join(ssh_folder, key)
)
key_details = {
"filename": key,
"format": parsed_key.get_name(),
"bits": parsed_key.get_bits(),
"fingerprint": parsed_key.get_fingerprint().hex(),
}
available_private_keys.append(key_details)
except (SSHException, UnicodeDecodeError, IsADirectoryError):
continue
return available_private_keys
示例9: execute
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def execute(self, command):
"""
Executes command on remote hosts
:type command: str
:param command: command to be run on remote host
"""
try:
if self.ssh.get_transport() is not None:
logger.debug('{0}: executing "{1}"'.format(self.target_address,
command))
stdin, stdout, stderr = self.ssh.exec_command(command)
return dict(zip(['stdin', 'stdout', 'stderr'],
[stdin, stdout, stderr]))
else:
raise SSHConnectionError(self.target_address,
"ssh transport is closed")
except (AuthenticationException, SSHException,
ChannelException, SocketError) as ex:
logger.critical(("{0} execution failed on {1} with exception:"
"{2}".format(command, self.target_address,
ex)))
raise SSHCommandError(self.target_address, command, ex)
示例10: execute_async
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def execute_async(self, command, callback=None):
"""
Executes command on remote hosts without blocking
:type command: str
:param command: command to be run on remote host
:type callback: function
:param callback: function to call when execution completes
"""
try:
logger.debug(('{0}: execute async "{1}"'
'with callback {2}'.format(self.target_address,
command,
callback)))
future = self.executor.submit(self.execute, command)
if callback is not None:
future.add_done_callback(callback)
return future
except (AuthenticationException, SSHException,
ChannelException, SocketError) as ex:
logger.critical(("{0} execution failed on {1} with exception:"
"{2}".format(command, self.target_address,
ex)))
raise SSHCommandError(self.target_address, command, ex)
示例11: upload_file
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def upload_file(self, local_path, remote_path):
"""
Upload a file from the local filesystem to the remote host
:type local_path: str
:param local_path: path of local file to upload
:type remote_path: str
:param remote_path: destination path of upload on remote host
"""
logger.debug("{0}: uploading {1} to {0}:{2}".format(self.target_address,
local_path,
remote_path))
try:
sftp = paramiko.SFTPClient.from_transport(self.transport())
sftp.put(local_path, remote_path)
sftp.close()
except SSHException as ex:
logger.warn(("{0}: LiME module upload failed with exception:"
"{1}".format(self.target_address, ex)))
示例12: get_specific_pkey
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def get_specific_pkey(self, name, offset, password):
self.iostr.seek(offset)
logging.debug('Reset offset to {}.'.format(offset))
logging.debug('Try parsing it as {} type key'.format(name))
pkeycls = getattr(paramiko, name+'Key')
pkey = None
try:
pkey = pkeycls.from_private_key(self.iostr, password=password)
except paramiko.PasswordRequiredException:
raise InvalidValueError('Need a passphrase to decrypt the key.')
except (paramiko.SSHException, ValueError) as exc:
self.last_exception = exc
logging.debug(str(exc))
return pkey
示例13: get_default_encoding
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def get_default_encoding(self, ssh):
commands = [
'$SHELL -ilc "locale charmap"',
'$SHELL -ic "locale charmap"'
]
for command in commands:
try:
_, stdout, _ = ssh.exec_command(command, get_pty=True)
except paramiko.SSHException as exc:
logging.info(str(exc))
else:
data = stdout.read()
logging.debug('{!r} => {!r}'.format(command, data))
result = self.parse_encoding(data)
if result:
return result
logging.warning('Could not detect the default encoding.')
return 'utf-8'
示例14: on_message
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def on_message(self, message):
logging.debug('{!r} from {}:{}'.format(message, *self.src_addr))
worker = self.worker_ref()
try:
msg = json.loads(message)
except JSONDecodeError:
return
if not isinstance(msg, dict):
return
resize = msg.get('resize')
if resize and len(resize) == 2:
try:
worker.chan.resize_pty(*resize)
except (TypeError, struct.error, paramiko.SSHException):
pass
data = msg.get('data')
if data and isinstance(data, UnicodeType):
worker.data_to_dst.append(data)
worker.on_write()
示例15: ssh_exec_command
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import SSHException [as 别名]
def ssh_exec_command(ssh_obj, cmd, prefix=''):
"""
Execute a command on the ssh connection.
:param ssh_obj: SSH object.
:param cmd: command to run.
:param prefix: Prefix to be used for printing
:return: stdout and stderr
"""
try:
print(prefix+ "[*] Running Command:" + cmd)
_, stdout_obj, stderr_obj = ssh_obj.exec_command(cmd)
exit_status = stdout_obj.channel.recv_exit_status()
if exit_status == 0:
print(prefix + GREEN_PRINT + "[+] Command:" + cmd + " Completed Successfully" + END_PRINT)
else:
print(prefix + RED_PRINT + "[*] Command:" + cmd + " Return Code:" + str(exit_status) + END_PRINT)
except paramiko.SSHException as e:
print(prefix + RED_PRINT + "[!] Problem occurred while running command: %s, Error: %s" % (cmd, e) + END_PRINT)
raise e
return stdout_obj, stderr_obj