How to ssh connect through Python Paramiko with ppk public key
Ok @Adam and @Kimvais were right, Paramiko cannot parse .ppk files.
So the way to go (thanks to @JimB too) is to convert .ppk file to OpenSSH private key format; this can be achieved using PuTTYgen as described here.
Then it's very simple getting connected with it:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('<hostname>', username='<username>', password='<password>', key_filename='<path/to/openssh-private-key-file>')
stdin, stdout, stderr = ssh.exec_command('ls')
print stdout.readlines()
ssh.close()
SSH using Python via private keys
SSHClient.connect
can handle public key authentication with a simple call:
import paramiko
ssh = paramiko.SSHClient()
ssh.connect(hostname, username=username, key_filename=key_path, password=passphrase)
The password
argument is used as a passphrase, when key_filename
is provided.
Additionally, you will also have to verify the server's host key (as you must have done with ssh
before). See Paramiko "Unknown Server".
Paramiko - connect with private key - not a valid OPENSSH private/public key file
I have a Paramiko RSA key authentication setup running. Here is a summary of what I did:
run ssh-keygen -t rsa to generate the id_rsa and id_rsa.pub files
copy contents of id_rsa.pub into ~/.ssh/authorized_keys (on the
target system)copy the id_rsa (private) keyfile onto the client machine
(on the target I have mode 755 on .ssh/ and 644 on authorized_keys)
The following code runs a login using Paramiko:
import logging
import paramiko
logger = paramiko.util.logging.getLogger()
hdlr = logging.FileHandler('app.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
k = paramiko.RSAKey.from_private_key_file('id_rsa')
ssh.connect('160.100.28.216', username='edwards', pkey = k)
sftp = ssh.open_sftp()
sftp.chdir('/home/edwards')
except Exception, err:
logging.debug(err)
logging.info('Error connecting to Host')
The following is seen in the app.log file:
2017-08-23 16:52:33,154 INFO Connected (version 2.0, client OpenSSH_6.6.1)
2017-08-23 16:52:46,926 INFO Authentication (publickey) successful!
2017-08-23 16:52:47,203 INFO [chan 0] Opened sftp connection (server version 3)
(NB: The Paramiko client is using the private key file.) This is all on Python 2.7.
SSH/SCP through Paramiko with key in string
Use RSAKey.from_private_key
:
ki = paramiko.RSAKey.from_private_key(private_key)
See How do use paramiko.RSAKey.from_private_key()?
The answer on the above question shows code for Python 3.
In Python 2.7, this works:
import os
import glob
import paramiko
import StringIO
private_key_file = StringIO.StringIO()
private_key_file.write('-----BEGIN RSA PRIVATE KEY-----\nMIIEoQIBAAKCAQEAvG9YlF2da0jJ5PvvlmVnVnYYFc7kkJuC0wvsACVuvep/sds5\nIEX0e+/rq9UBj/V3rzsvbHzb6IVulSjEqcM32NA4SyqR1m5jAj/WVDXQcxzruBDO\nZbdNhDS1T4+HckTWzttAE4o83bRju+3BhR9CtrDtt+7CSei4MccSMEH7yxo1BGuL\nONfkhB6qAWh55T6tamTyjLg9R9xqBkG6x3ZmoOB9j/11P5awuUoE1DfbqQ3KMLSR\nr64unavECfBaBYvuxlWbxRJFAN8C95oE+Kbc1g1bEL9du6FIeHZ/eaBbkcl84Fm7\nswdHBnd7+tqfo4TGzvbEW4H2ZQLiuiGK23ao0wIBJQKCAQEAiYGvV4KVd81VDuFb\nzp0GOCypyrmSCKjVFowowdYgYRLnj5/5QRB0IxbcaKJbFgYm56e60qBNclOIC/sn\nuiasNm5uRLBclY7SoMbM1aq6tN3AxJakc70c4+8chip3mJMZStdYRZw6QOtrX5+o\n5JpFcI7yqNDS96nShTBnN/jMf3K6yjQjvTv/DJi9SHJ6dTtrY1AuUNEoiO3cwgeH\nFks169756L+fpweL4VjQl4UyClL0bwHWpe579XzjBV0AlGu1tHaE5zslTPtGw1lg\nnZhj/7skZKAIGQxIzfmGv4QEcvePKYzM8EUhOr/0O3BHjLC0lp5hMwmsPJfaHlMb\nBak0JQKBgQD0cRu65WNkCcRlpuUvp5/kiMvu7PmcFUsY6dMeV0bL4oQ+PCqfwXFj\nhkyS7V2DJnllYPwi6E68soie+IL1blmY7hWcoznJ48PWJ0bJmqBgzhpC623RtTKS\ny/O0IbrGKPpaRGfD/PAvqJOpwx7Im2k6/UVQ0OYSurC8CB3BDRTCXQKBgQDFWEq7\ny2SntPFA9zu+31bW57lb26l8nNmUXmRLnXyvqomAkCGSadiW/i5nBEBDV/zJ/rXp\n0QWrmrpfvjnMF6g26m4sj6Pfs5zoSV1+FEidqYDcytUPJnpR55Ulpshf57TGuFbx\n1SCnda1dmm3TzAzzKTc6MbSPV0krMyAgCP7E7wKBgFXijTPUDioRRQEe9pQz+eiD\nFzhFbHUcPPrqXu78EfSbsexaVCpK4qZtdNmtWDT/rhyzX4Hi6zthUpi4LgM0nAVM\nu3w5WX5JG0s+O3dEKoLgoXF1UBk/qfw50iqIZDfJNV38W889McuOQbgvzIusObrH\nsJIENSks1k/nLQx6N7npAoGAUAEzDdzVx3LeWJuUwwCY06oM4Azxrw8nxochvco5\nd6YAZI11ZN7NbaVRFQG5MA7p8QZlbKDYyQdgUFQJl+3qP8bSuB6Oix9Ncu1Panbt\nAaWVGz14+E3ej+hDYkqIlZVJSaStoE978NyuETDEvaXAD40/5yjoVclwsKYGGtM2\n2jcCgYA6v1tvd2QdDeijiSRnXAeJ1hDLB8Jj2WJqnDZ7dQ5+XTIKfY4POIpHCPx8\n6Uk4NCnyJGmBHog1M7Bjb/o0c1UTid6CNBI4ciVaRyXXcy6Czup2EhkiNGom2883\n8+9pdxShKf0pJCqdZxJdVmg1NHZnr20PwN7PASbVcRg3t+wt2g==\n-----END RSA PRIVATE KEY-----')
private_key_file.seek(0)
ki = paramiko.RSAKey.from_private_key(private_key_file)
How to connect to an SFTP server through Paramiko with a PPK key?
Based on the posted logs and this question, I have finally managed to solve the error with disabling rsa-sha2-512 and rsa-sha2-256 algorithms to force the ssh-rsa algorithm.
ssh_client.connect(
disabled_algorithms={'pubkeys': ['rsa-sha2-512', 'rsa-sha2-256']}, ...)
Connecting to SFTP server with .ppk key using Python pysftp: not a valid DSA private key file
For your literal problem, see:
How to ssh connect through Python Paramiko with ppk public key
It's about Paramiko. But pysftp is just a thin wrapper around Paramiko. And you should not use pysftp anyway, it's dead. See pysftp vs. Paramiko.
Though note, that as you have WinSCP working, you can automate your task using WinSCP scripting.
WinSCP GUI can even generate a working script template for you.
Passwordless SSH connection with Paramiko fails where as with SSH works
Your ssh
connection works, because it uses a private key from ~/.ssh/id_rsa_c2c
(as configured in ssh_config
). The .ssh
folder and ssh_config
file serve as a configuration for OpenSSH toolset (ssh
in this case). You cannot expect that other SSH clients/libraries will use OpenSSH configuration files. They won't, in general.
If you want to use public key authentication with Paramiko, use key_filename
argument of SSHClient.connect
.
See also How to ssh connect through python Paramiko with ppk public key.
Though Paramiko, in particular, would use a key file, if it had a common name like id_rsa
, id_dsa
, etc. See Force password authentication (ignore keys in .ssh folder) in Paramiko in Python for exactly opposite problem.
Obligatory warning: Do not use AutoAddPolicy
, unless you do not care about security. You are losing a protection against MITM attacks this way.
For a correct solution, see Paramiko "Unknown Server".
Loading key from an SSH jumphost using Paramiko
Yes. You have to have all credentials locally. The port forwarding alone does not make credentials stored on the intermediate hosts available for authentication.
Of course, you can use SFTP to access/download the files/keys, like:
sftp3 = ssh3.open_sftp()
with sftp3.open(".ssh/id_rsa") as key_file:
pkey = RSAKey.from_private_key(key_file)
ssh4.connect(host4, username=host4_username, sock=vmchannel, pkey=pkey)
Related Topics
Import CSV with Different Number of Columns Per Row Using Pandas
Pip Broke. How to Fix Distributionnotfound Error
How to Upload a File to Directory in S3 Bucket Using Boto
Is Generator.Next() Visible in Python 3
How to Create an Object for a Django Model with a Many to Many Field
Convert Pandas Series to Dataframe
Understanding Time.Perf_Counter() and Time.Process_Time()
[] and {} VS List() and Dict(), Which Is Better
Detect Text Region in Image Using Opencv
How to Implement Band-Pass Butterworth Filter with Scipy.Signal.Butter
Scrapy - How to Manage Cookies/Sessions
Is There a Module for Balanced Binary Tree in Python's Standard Library
How to Run a Python Script in a Web Page
Add Column with Number of Days Between Dates in Dataframe Pandas
Matplotlib: How to Draw a Rectangle on Image
How to Specify "Nullable" Return Type with Type Hints