Python SFTP Paramiko:捕获错误的主机名错误

Python SFTP Paramiko: catch Wrong Hostname Error

我目前正在测试用户名或主机错误时的异常,但我不知道应该捕获哪个异常。 我试过 BadHostkeyException 但显然那是错误的。 如果我抓到 socket.gaierror 那就太模糊了。

我得到这个输出:

  File "./sFTPscript10.py", line 141, in connSFTP
    c.connect( hostname = config.host, username = config.username, pkey = k )
  File "/usr/local/lib/python3.6/site-packages/paramiko/client.py", line 340, in connect
    to_try = list(self._families_and_addresses(hostname, port))
  File "/usr/local/lib/python3.6/site-packages/paramiko/client.py", line 204, in _families_and_addresses
    hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM
  File "/usr/lib64/python3.6/socket.py", line 745, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

我的代码:

def connSFTP(config,logger_info,logger_error,resetConnSFTP,logger_error_mail,reset):
    #Fehleroptionen 1. Pfad zum SSH-KeyError
                        #-SSH-Key vorhanden?
                    #2.Host und/oder Username ist falsch
    try:
        k = paramiko.RSAKey.from_private_key_file(config.ssh_key_filepath) #SSH KEY
        c = paramiko.SSHClient()
        c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        c.connect( hostname = config.host, username = config.username, pkey = k )
        sftp = c.open_sftp()
        logger_info.info('Connected with '+ config.host)

        return sftp

    except (paramiko.BadHostKeyException) as err:
        print('Username or Host is wrong' + str(err))

你自己看,异常是socket.gaierror。没有更具体的例外。

您可以检查 errno 以获得更具体的错误(在您的情况下为 -2)。但请注意,它不会独立于平台。

except socket.gaierror as e:
    print(e.errno)