Python paramiko 模块,BadHostKeyException() 实例源码

我们从Python开源项目中,提取了以下17个代码示例,用于说明如何使用paramiko.BadHostKeyException()

项目:galaxia    作者:WiproOpenSourcePractice    | 项目源码 | 文件源码
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)
项目:node-gn    作者:Shouqun    | 项目源码 | 文件源码
def connect(self, num_retries=5):
        retry = 0
        while retry < num_retries:
            try:
                self._ssh_client.connect(self.server.hostname,
                                         username=self.uname,
                                         pkey=self._pkey)
                return
            except socket.error, (value, message):
                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'
项目:galaxia    作者:WiproOpenSourcePractice    | 项目源码 | 文件源码
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
项目:galaxia    作者:WiproOpenSourcePractice    | 项目源码 | 文件源码
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
项目:awslambdamonitor    作者:gene1wood    | 项目源码 | 文件源码
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))
项目:Chromium_DepotTools    作者:p07r0457    | 项目源码 | 文件源码
def connect(self, num_retries=5):
        retry = 0
        while retry < num_retries:
            try:
                self._ssh_client.connect(self.server.hostname,
                                         username=self.uname,
                                         pkey=self._pkey)
                return
            except socket.error, (value, message):
                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'
项目:depot_tools    作者:webrtc-uwp    | 项目源码 | 文件源码
def connect(self, num_retries=5):
        retry = 0
        while retry < num_retries:
            try:
                self._ssh_client.connect(self.server.hostname,
                                         username=self.uname,
                                         pkey=self._pkey)
                return
            except socket.error, (value, message):
                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'
项目:Remote_raspberrypi_GPIO_Control    作者:Rahul14singh    | 项目源码 | 文件源码
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
项目:cluster-genesis    作者:open-power-ref-design-toolkit    | 项目源码 | 文件源码
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_
项目:cluster-genesis    作者:open-power-ref-design-toolkit    | 项目源码 | 文件源码
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))
项目:cuny-bdif    作者:aristotle-tek    | 项目源码 | 文件源码
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')
项目:astoptool    作者:zouliuyun    | 项目源码 | 文件源码
def _connect(self,ip,port,user,sock=None):
        sshClient = paramiko.SSHClient()
        sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        tries = 0
        sshtry = state.sshtry
        sshTimeOut = state.sshTimeOut
        while True:
            try:
                tries += 1
                sshClient.connect(ip,int(port),user,timeout=sshTimeOut,sock=sock,key_filename=["/home/astd/.ssh/authorized_keys","/home/astd/.ssh/id_rsa"])
                sshClient = sshClient
                return sshClient
            except paramiko.BadHostKeyException, e:
                raise NetworkError("Host key for %s did not match pre-existing key! Server's key was changed recently, or possible man-in-the-middle attack." % ip, e)
            except (
                paramiko.AuthenticationException,
                paramiko.PasswordRequiredException,
                paramiko.SSHException
            ), e:
                msg = str(e)
                #if e.__class__ is paramiko.SSHException and msg == 'Error reading SSH protocol banner':
                if e.__class__ is paramiko.SSHException and msg.startswith('Error reading SSH protocol banner'):
                    #print "WARNNING: reconnect ip:%s %s"%(self.ip,msg)
                    if tries < sshtry:
                        time.sleep(1)
                        continue
                    else:
                        raise Exception(e)
                else:
                    raise Exception(e)
            except Exception,e:
                if str(e) == "timed out" and tries < sshtry:
                    #print "Warnning %s:%s,retries ..."%(ip,str(e))
                    time.sleep(1)
                    continue
                raise e
项目:astoptool    作者:zouliuyun    | 项目源码 | 文件源码
def __init__(self,ip,port=22,user="astd"):
        self.ip = ip
        self.port = port
        self.user = user
        sshClient = paramiko.SSHClient()
        sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        tries = 0
        sshtry = state.sshtry
        while True:
            try:
                tries += 1
                sshClient.connect(ip,port,user,timeout=5,key_filename=["/home/astd/.ssh/authorized_keys","/home/astd/.ssh/id_rsa"])
                self.sshClient = sshClient
                self.transport = sshClient.get_transport()
                break
            except paramiko.BadHostKeyException, e:
                raise NetworkError("Host key for %s did not match pre-existing key! Server's key was changed recently, or possible man-in-the-middle attack." % ip, e)
            except (
                paramiko.AuthenticationException,
                paramiko.PasswordRequiredException,
                paramiko.SSHException
            ), e:
                msg = str(e)
                if e.__class__ is paramiko.SSHException and msg == 'Error reading SSH protocol banner':
                    if tries < sshtry:
                        continue
                    else:
                        raise Exception(e)
                else:
                    raise Exception(e)
            except Exception,e:
                raise Exception(e)
项目:astoptool    作者:zouliuyun    | 项目源码 | 文件源码
def connect(self):
        sshClient = paramiko.SSHClient()
        sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        tries = 0
        sshtry = state.sshtry
        while True:
            try:
                tries += 1
                sshClient.connect(self.ip,self.port,self.user,timeout=15,key_filename=["/home/astd/.ssh/authorized_keys","/home/astd/.ssh/id_rsa"])
                self.sshClient = sshClient
                self.transport = sshClient.get_transport()
                break
            except paramiko.BadHostKeyException, e:
                raise NetworkError("Host key for %s did not match pre-existing key! Server's key was changed recently, or possible man-in-the-middle attack." % ip, e)
            except (
                paramiko.AuthenticationException,
                paramiko.PasswordRequiredException,
                paramiko.SSHException
            ), e:
                msg = str(e)
                #if e.__class__ is paramiko.SSHException and msg == 'Error reading SSH protocol banner':
                if e.__class__ is paramiko.SSHException and msg.startswith('Error reading SSH protocol banner'):
                    #print "WARNNING: ip:%s %s"%(self.ip,msg)
                    if tries < sshtry:
                        time.sleep(1)
                        continue
                    else:
                        raise Exception(e)
                else:
                    raise Exception(e)
            except Exception,e:
                raise Exception(e)
项目:learneveryword    作者:karan    | 项目源码 | 文件源码
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')
项目:alfred-ec2    作者:SoMuchToGrok    | 项目源码 | 文件源码
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')
项目:appetite    作者:Bridgewater    | 项目源码 | 文件源码
def get_ssh_client(hostname, ssh_hostname):
        """Tries to create ssh client

        Create ssh client based on the username and ssh key
        """

        if not CREDS.SSH_KEYFILE:
            logger.errorout("ssh_keyfile not set",
                            module=COMMAND_MODULE_CUSTOM)

        retries = 0

        while retries < MAX_SSH_RETRIES:
            try:
                ssh = paramiko.SSHClient()
                ssh.load_system_host_keys()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

                ssh.connect(hostname=ssh_hostname,
                            username=CREDS.SSH_USER,
                            port=CREDS.SSH_PORT,
                            pkey=CREDS.PK,
                            timeout=CONNECTION_TIMEOUT)

                return ssh
            except paramiko.BadAuthenticationType:
                logger.error("BadAuthenticationType",
                             hostname=hostname,
                             module=COMMAND_MODULE_CUSTOM)
                return
            except paramiko.AuthenticationException:
                logger.error("Authentication failed",
                             hostname=hostname,
                             module=COMMAND_MODULE_CUSTOM)
                return
            except paramiko.BadHostKeyException:
                logger.error("BadHostKeyException",
                             fix="Edit known_hosts file to remove the entry",
                             hostname=hostname,
                             module=COMMAND_MODULE_CUSTOM)
                return
            except paramiko.SSHException:
                logger.error("SSHException",
                             hostname=hostname,
                             module=COMMAND_MODULE_CUSTOM)
                return
            except Exception as e:
                if retries == 0:
                    logger.error("Problems connecting to host",
                                 hostname=hostname,
                                 module=COMMAND_MODULE_CUSTOM,
                                 error=e.message)
                retries += 1
                time.sleep(1)

        logger.error("Can not connect to host",
                     hostname=hostname,
                     module=COMMAND_MODULE_CUSTOM)

        return None