I'm trying to connect with an SFTP through an RSA Key pair that I generated. The server already added the public key to the server and I can access it using Filezilla. I'm following this post Verify host key with pysftp
However, I'm still getting the same error
C:\Users\John.Doe\Anaconda3\envs\EC_automation\lib\site-packages\pysftp\__init__.py:61: UserWarning: Failed to load HostKeys from C:\Users\John.Doe\.ssh\known_hosts. You will need to explicitly load HostKeys (cnopts.hostkeys.load(filename)) or disableHostKey checking (cnopts.hostkeys = None).
warnings.warn(wmsg, UserWarning)
Exception ignored in: <function Connection.__del__ at 0x00000256882C5C10>
Traceback (most recent call last):
File "C:\Users\John.Doe\Anaconda3\envs\EC_automation\lib\site-packages\pysftp\__init__.py", line 1013, in __del__
self.close()
File "C:\Users\John.Doe\Anaconda3\envs\EC_automation\lib\site-packages\pysftp\__init__.py", line 784, in close
if self._sftp_live:
AttributeError: 'Connection' object has no attribute '_sftp_live'
I'm using an anaconda virtual env under Python 3 under windows server 2016. This is my code
logging.info('Establishing connection with SFTP hosted in {}'.format(secrets.FTP_SERVER))
priv_key_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'SSH keys', 'PrivateKeyDev.ppk')
logging.info('Key-based authentication. Keys in {}'.format(priv_key_path))
logging.debug('Adding keys to connection through cnopts')
cnopts = pysftp.CnOpts()
cnopts.hostkeys.add(secrets.FTP_SERVER, 'ssh-rsa', priv_key_path)
try:
pysftp.Connection(secrets.FTP_SERVER, username=secrets.FTP_USER, cnopts=cnopts, private_key=priv_key_path, private_key_pass=secrets.KEY_PASS)
logging.info('Connection with FTP server established')
except:
logging.error('Unable to connect with {}'.format(secrets.FTP_SERVER))
sys.exit()
I don't understand what's wrong with my approach. I can see the host in hostkeys
EDIT
setting cnopts.hostkeys = None
and changing the format of the key to PEM resolves the issue, now the question is, how bad is to do this in production if this is using an internal network?
2nd EDIT
Thanks to the comments I realized I had a problem with the key I'm tryingg to add to the Host keys that contain public keys by definition. so I tried to add the public key instead of the private but didn't work either. Same error.
cnopts.hostkeys.add(secrets.FTP_SERVER, 'ssh-rsa', pub_key_path)