paramiko - connect with private key - not a valid OPENSSH private/public key file

邮差的信 提交于 2019-12-03 21:37:09

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. I hope some or all of this may be useful.

You can convert id_rsa to RSA type private key with ssh-keygen. I faced the similar situation and it worked for me.

To Convert "BEGIN OPENSSH PRIVATE KEY" to "BEGIN RSA PRIVATE KEY"

ssh-keygen -p -m PEM -f ~/.ssh/id_rsa
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!