Skip to content

Instantly share code, notes, and snippets.

@chadgroom
Last active January 27, 2022 14:13
Show Gist options
  • Save chadgroom/d7e3ad53fda7854b45dcd24a346720f2 to your computer and use it in GitHub Desktop.
Save chadgroom/d7e3ad53fda7854b45dcd24a346720f2 to your computer and use it in GitHub Desktop.
Correct way to load ecdsa keys with paramiko/pysftp with OpenSSH.. Solves issue: https://github.com/paramiko/paramiko/issues/350
#!/usr/bin/env python3
# This error is caused by using `paramiko.RSA()` to manually load an ecdsa key from your know_hosts file or for manually loading as bytes.
# Using: `key = paramiko.AgentKey()` instead seemingly detects the key type automatically and accepts the ecdsa-sha2-nistp256 key just fine.
# EXAMPLE:
import pysftp
from base64 import decodebytes
import paramiko
hostname = "123.10.20.30"
password = "password123"
port = 2222
keydata = b"""BBBBE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBMGAGLpMKIeSkLkOizv78dfOVG+V2YGInryO/tPV3onFfUAm8zVHLfOIagbpqJI09UblO+ujSM+ZPN0ERnD6uSA="""
# LOAD THE ECDSA KEY
key = paramiko.AgentKey('ecdsa-sha2-nistp256', decodebytes(keydata))
# SET OPTS
cnopts = pysftp.CnOpts()
# ADD OUR KEY TO OPTS
cnopts.hostkeys.add(hostname, 'ecdsa-sha2-nistp256', key)
# CONNECT
with pysftp.Connection(hostname, port=port, username='root', password=password, cnopts=cnopts) as sftp:
print("Connected!")
with sftp.cd('/usr/share'):
print("In remote /usr/share!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment