How to include the private key in paramiko after fetching from string?

浪子不回头ぞ 提交于 2019-12-05 08:33:21

if you cannot save the private keys to files, that would be the the main reason to use StringIO: StringIO takes a string and turns it into a file-like object, but nothing is written to the file system. It allows you to pass in file-like objects when all you have is a string: i.e. exactly cases like this.

import paramiko, StringIO

key_string = "------" # I saved my key in this string
not_really_a_file = StringIO.StringIO(key_string)
private_key = paramiko.RSAKey.from_private_key(not_really_a_file)

not_really_a_file.close()

That works for me, and you should be able to connect with that object:

client = paramiko.SSHClient()
client.set_missing_key_policy(paramiko.AutoAddPolicy())
client.connect(host="example.com", username="root", pkey=private_key)

You can use StringIO for creating file-like object with your stored private key and PKey's class method from_private_key, so you will create PKey instance and you can pass it to connect method.

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