在Paramiko应用程序中嵌入密钥作为字符串

2024-09-28 23:16:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用Python创建一个可执行文件,并将Paramiko用于SSH。我需要消除外部文件,如私钥文件,并尝试去嵌入字符串

我尝试了此解决方案,但对我无效:
Paramiko: Creating a PKey from a public key string

我如何做到这一点?谢谢


Tags: 文件key字符串fromcreating可执行文件paramikostring
2条回答

您提到的解决方案:

key = paramiko.RSAKey(data=base64.b64decode('AAblablabla...'))

工作正常,但以base64格式存储密钥可能不方便

以下代码显示了如何使用以“纯文本”格式存储的密钥(作为~/.ssh目录中的密钥文件):

import paramiko
import StringIO

my_key = """\
  -BEGIN RSA PRIVATE KEY  -
<your key here>
  -END RSA PRIVATE KEY  -"""

pkey = paramiko.RSAKey.from_private_key(StringIO.StringIO(my_key))

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='host', username='user', pkey=pkey)

...

ssh.close()

在Python 3中:

import io
# ...
pkey = paramiko.RSAKey.from_private_key(io.StringIO(my_key))

StringIO in Python3

要从ssh客户端上的字符串中添加公钥,必须设置关键字arg look\u for\u keys=False,然后使用MissingHostKeyPolicy classes missing\u host\u key()方法从字符串中添加密钥

my_pub_key = "xx.xx.xx.xx ecdsa-sha2-nistp256 mlzdHAyNT....."
my_host = my_pub_key.split(' ')[0]
password = 'myFavortitePassword'
username = 'myUsername'

ssh_client=paramiko.SSHClient()

host_key_policy = paramiko.MissingHostKeyPolicy()
host_key_policy.missing_host_key(ssh_client, my_host, my_pub_key)

ssh_client.connect(hostname= my_host
                            ,username=username
                            ,password=password
                            ,port=22
                            ,look_for_keys=False)

相关问题 更多 >