I'd like to catch nicely the error when "No hostkey for host *** is found" and give an appropriate message to the end user. I tried this:
import pysftp, paramiko
try:
with pysftp.Connection('1.2.3.4', username='root', password='') as sftp:
sftp.listdir()
except paramiko.ssh_exception.SSHException as e:
print('SSH error, you need to add the public key of your remote in your local known_hosts file first.', e)
but unfortunately the output is not very nice:
SSH error, you need to add the public key of your remote in your local known_hosts file first. No hostkey for host 1.2.3.4 found.
Exception ignored in: <function Connection.__del__ at 0x00000000036B6D38>
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\pysftp\__init__.py", line 1013, in __del__
self.close()
File "C:\Python37\lib\site-packages\pysftp\__init__.py", line 784, in close
if self._sftp_live:
AttributeError: 'Connection' object has no attribute '_sftp_live'
How to nicely avoid these last lines / this "exception ignored" with a try: except:
?
The analysis by @reverse_engineer is correct. However:
self._transport
, also is defined too late.pysftp.Connection
class as follows:Update
I could not duplicate this error on my desktop. However, I see in the source for
pysftp
in the code where it initializes its_cnopts
attribute withself._cnopts = cnopts or CnOpts()
wherecnopts
is a keyword parameter to thepysftp.Connection
constructor and there is a possibilty of theCnOpts
constructor throwing aHostKeysException
exception if no host keys are found resulting in the_cnopts
attribute not being set.Try the following updated code and let me know if it works: