本文整理汇总了Python中paramiko.BadHostKeyException方法的典型用法代码示例。如果您正苦于以下问题:Python paramiko.BadHostKeyException方法的具体用法?Python paramiko.BadHostKeyException怎么用?Python paramiko.BadHostKeyException使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类paramiko
的用法示例。
在下文中一共展示了paramiko.BadHostKeyException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fetch_remote_crashes
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [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: ssh_connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def ssh_connect(self):
ssh = paramiko.SSHClient()
ssh._system_host_keys = self.settings['system_host_keys']
ssh._host_keys = self.settings['host_keys']
ssh.set_missing_host_key_policy(self.settings['policy'])
args = self.get_args()
dst_addr = (args[0], args[1])
logging.info('Connecting to {}:{}'.format(*dst_addr))
try:
ssh.connect(*args, timeout=6)
except socket.error:
raise ValueError('Unable to connect to {}:{}'.format(*dst_addr))
except paramiko.BadAuthenticationType:
raise ValueError('Authentication failed.')
except paramiko.BadHostKeyException:
raise ValueError('Bad host key.')
chan = ssh.invoke_shell(term='xterm')
chan.setblocking(0)
worker = Worker(ssh, chan, dst_addr)
IOLoop.current().call_later(DELAY, recycle, worker)
return worker
示例3: ssh_connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def ssh_connect(self, args):
ssh = self.ssh_client
dst_addr = args[:2]
logging.info('Connecting to {}:{}'.format(*dst_addr))
try:
ssh.connect(*args, timeout=options.timeout)
except socket.error:
raise ValueError('Unable to connect to {}:{}'.format(*dst_addr))
except paramiko.BadAuthenticationType:
raise ValueError('Bad authentication type.')
except paramiko.AuthenticationException:
raise ValueError('Authentication failed.')
except paramiko.BadHostKeyException:
raise ValueError('Bad host key.')
term = self.get_argument('term', u'') or u'xterm'
chan = ssh.invoke_shell(term=term)
chan.setblocking(0)
worker = Worker(self.loop, ssh, chan, dst_addr)
worker.encoding = options.encoding if options.encoding else \
self.get_default_encoding(ssh)
return worker
示例4: loginandrun
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def loginandrun(hostname,uname,pwd,command):
try:
log.info("Establishing ssh connection")
client = getsshClient()
client.load_system_host_keys()
client.connect(hostname)#,username=uname)#,password=pwd)
except paramiko.AuthenticationException:
print("Authentication failed, please verify your credentials: %s")
except paramiko.SSHException as sshException:
print("Unable to establish SSH connection: %s" % sshException)
except paramiko.BadHostKeyException as badHostKeyException:
print("Unable to verify server's host key: %s" % badHostKeyException)
try:
stdin, stdout, stderr = client.exec_command(command)
result = stderr.read()
if len(result) > 0:
print("hit error" + result)
except Exception as e:
print("Operation error: %s", e)
# Any new implementation to use this method
示例5: loginandcopydir
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def loginandcopydir(hostname,uname,pwd,sfile,tfile,recursive,preserve_times):
try:
log.info("Establishing ssh connection")
client = getsshClient()
client.load_system_host_keys()
client.connect(hostname) #,username=uname)#,password=pwd)
except paramiko.AuthenticationException:
print("Authentication failed, please verify your credentials: %s")
except paramiko.SSHException as sshException:
print("Unable to establish SSH connection: %s" % sshException)
except paramiko.BadHostKeyException as badHostKeyException:
print("Unable to verify server's host key: %s" % badHostKeyException)
except Exception as e:
print(e.args)
try:
scpclient = scp.SCPClient(client.get_transport())
scpclient.put(sfile,tfile,recursive,preserve_times)
except scp.SCPException as e:
print("Operation error: %s", e)
# Deprecated
示例6: loginandcopy
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def loginandcopy(hostname,uname,pwd,sfile,tfile):
try:
log.info("Establishing ssh connection")
client = getsshClient()
client.load_system_host_keys()
client.connect(hostname)#,username=uname)#,password=pwd)
except paramiko.AuthenticationException:
print("Authentication failed, please verify your credentials: %s")
except paramiko.SSHException as sshException:
print("Unable to establish SSH connection: %s" % sshException)
except paramiko.BadHostKeyException as badHostKeyException:
print("Unable to verify server's host key: %s" % badHostKeyException)
except Exception as e:
print(e.args)
try:
log.info("Getting SCP Client")
scpclient = scp.SCPClient(client.get_transport())
log.info(scpclient)
log.info("Hostname: %s", hostname)
log.info("source file: %s", sfile)
log.info("target file: %s", tfile)
scpclient.put(sfile,tfile)
except scp.SCPException as e:
print("Operation error: %s", e)
示例7: connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def connect(self):
retry = 0
while retry < 5:
try:
self._ssh_client.connect(self.server.hostname,
username=self.uname,
pkey=self._pkey)
return
except socket.error, (value,message):
if value == 61 or value == 111:
print 'SSH Connection refused, will retry in 5 seconds'
time.sleep(5)
retry += 1
else:
raise
except paramiko.BadHostKeyException:
print "%s has an entry in ~/.ssh/known_hosts and it doesn't match" % self.server.hostname
print 'Edit that file to remove the entry and then hit return to try again'
raw_input('Hit Enter when ready')
retry += 1
示例8: __init__
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def __init__(self, host, ssh_log=False, username=None,
password=None, look_for_keys=True, key_filename=None):
paramiko.SSHClient.__init__(self)
self.host = host
self.log = logger.getlogger()
self.ssh_log = SSH_LOG
if ssh_log and logger.is_log_level_file_debug():
paramiko.util.log_to_file(self.ssh_log)
if key_filename is None:
self.load_system_host_keys()
self.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
self.connect(
host,
username=username,
password=password,
look_for_keys=look_for_keys,
key_filename=key_filename)
except (
paramiko.BadHostKeyException,
paramiko.AuthenticationException,
paramiko.SSHException,
socket.error,
BaseException) as exc:
self.log.error('%s: %s' % (host, str(exc)))
raise SSH_Exception('Connection Failure - {}'.format(exc))
示例9: connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def connect(self):
"""
Connect to the SSH server and authenticate to it
"""
self._socket = paramiko.SSHClient()
self._socket.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
self._socket.connect(
hostname=self.hostname,
username=self.username,
password=self.password,
timeout=self._timeout,
port=int(self.port),
allow_agent=False,
look_for_keys=False,
)
self._stdin, self._stdout, self._stderr = self._socket.exec_command(
"", get_pty=False
)
except (
paramiko.BadHostKeyException,
paramiko.AuthenticationException,
paramiko.SSHException,
) as e:
raise GvmError("SSH Connection failed", e)
示例10: execute_cmd_over_ssh
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def execute_cmd_over_ssh(host, cmd, private_key):
"""Run the given command over ssh
Using paramiko package, it creates a connection to the given host;
executes the required command on it and returns the output.
:param host: Dictionary of ip, username and password
:param cmd: Command to be run over ssh
:param private_key: path to private key file
:return: Output of the executed command
"""
LOG.debug('EXECUTE COMMAND <%s> OVER SSH', cmd)
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
k = paramiko.RSAKey.from_private_key_file(private_key)
try:
client.connect(host["ip"], username=host["username"], pkey=k)
except paramiko.BadHostKeyException as e:
raise Exception(
"BADHOSTKEY EXCEPTION WHEN CONNECTING TO %s", host["ip"], e)
except paramiko.AuthenticationException as e:
raise Exception(
"AUTHENTICATION EXCEPTION WHEN CONNECTING TO %s", host["ip"], e)
except paramiko.SSHException as e:
raise Exception("SSH EXCEPTION WHEN CONNECTING TO %s", host["ip"], e)
except socket.error as e:
raise Exception("SOCKET ERROR WHEN CONNECTING TO %s", host["ip"], e)
LOG.debug("CONNECTED TO HOST <%s>", host["ip"])
try:
stdin, stdout, stderr = client.exec_command(cmd)
return stdout.read().splitlines()
except paramiko.SSHException as e:
raise Exception("SSHEXCEPTION WHEN CONNECTING TO %s", host["ip"], e)
finally:
client.close()
示例11: test_is_missing_host_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [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)
示例12: is_missing_host_key
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [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)
示例13: connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def connect(self):
"""
Connect to the given hostname, using the provided credentials
Args:
None
Return:
None
Raise:
paramiko.BadHostKeyException: if host key is not readable
paramiko.AuthenticationException: if authentication failed
"""
try:
self.ssh_client.connect(self.hostname, port=self.port,
username=self.username,
password=self.password, pkey=self.pkey,
key_filename=self.key_filename,
timeout=self.connect_timeout,
allow_agent=self.allow_agent,
look_for_keys=self.look_for_keys)
except paramiko.BadHostKeyException:
print "[FATAL]: Server's host key could not be retrieved"
raise
except paramiko.AuthenticationException:
print "[FATAL]: Authentication failed"
raise
except Exception, exc:
print ("Unknown exception while connecting to server: ",
self.hostname, exc)
raise
示例14: connect
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def connect(self, num_retries=5):
"""
Connect to an SSH server and authenticate with it.
:type num_retries: int
:param num_retries: The maximum number of connection attempts.
"""
retry = 0
while retry < num_retries:
try:
self._ssh_client.connect(self.server.hostname,
username=self.uname,
pkey=self._pkey,
timeout=self._timeout)
return
except socket.error as xxx_todo_changeme:
(value, message) = xxx_todo_changeme.args
if value in (51, 61, 111):
print('SSH Connection refused, will retry in 5 seconds')
time.sleep(5)
retry += 1
else:
raise
except paramiko.BadHostKeyException:
print("%s has an entry in ~/.ssh/known_hosts and it doesn't match" % self.server.hostname)
print('Edit that file to remove the entry and then hit return to try again')
raw_input('Hit Enter when ready')
retry += 1
except EOFError:
print('Unexpected Error from SSH Connection, retry in 5 seconds')
time.sleep(5)
retry += 1
print('Could not establish SSH connection')
示例15: exec_cmd
# 需要导入模块: import paramiko [as 别名]
# 或者: from paramiko import BadHostKeyException [as 别名]
def exec_cmd(self, ip_addr, username, password, cmd,
ssh_log=False, look_for_keys=True, key_filename=None):
self.ssh_log = SSH_LOG
if ssh_log and logger.is_log_level_file_debug():
paramiko.util.log_to_file(self.ssh_log)
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(
ip_addr,
port=self.SWITCH_PORT,
username=username,
password=password,
look_for_keys=look_for_keys,
key_filename=key_filename)
except (
paramiko.BadHostKeyException,
paramiko.AuthenticationException,
paramiko.SSHException,
socket.error,
BaseException) as exc:
self.log.error('%s: %s' % (ip_addr, str(exc)))
raise SSH_Exception('SSH connection Failure - {}'.format(exc))
# sys.exit(1)
try:
_, stdout, stderr = ssh.exec_command(cmd)
except paramiko.SSHException as exc:
self.log.error('%s: %s, %s' % (ip_addr, str(exc), stderr.read()))
sys.exit(1)
stdout_ = stdout.read()
stderr_ = stderr.read()
status = stdout.channel.recv_exit_status()
ssh.close()
return status, stdout_, stderr_