简体   繁体   中英

Python SFTP Paramiko: catch Wrong Hostname Error

I am currently testing an exception for when the username or host is wrong but I don't know which exception I should catch. I tried BadHostkeyException but apparently that was wront. If I catch socket.gaierror then that would be to vague.

I am getting this Output:

  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

My Code:

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))

You can see yourself that the exception is socket.gaierror . There's no more specific exception.

You can check the errno for more specific error (-2 in your case). But note that it won't be platform independent.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM