" ssh-keygen -t rsa"在python中使用pexpect不会按预期生成公共文件

时间:2018-02-17 08:35:50

标签: python ssh pexpect

执行" ssh-keygen -t rsa"命令在python中使用pexpect,该命令不会生成" id_rsa.pub"按预期文件,有时.ssh文件夹将为空,有时包含"已知主机"文件。

以下是python代码片段:

import pexpect
command = 'ssh-keygen -t rsa'
print command
child = pexpect.spawn(command)
child.delaybeforesend=5
file_prompt = 'Enter file'
pwd_prompt = 'passphrase'
empty_string = '\n'
res = child.expect([pexpect.EOF,pexpect.TIMEOUT,file_prompt])
child.sendline(empty_string)
res = child.expect([pexpect.EOF,pexpect.TIMEOUT,pwd_prompt])
child.sendline(empty_string)
res = child.expect([pexpect.EOF,pexpect.TIMEOUT,pwd_prompt])
child.sendline(empty_string)
res = child.expect([pexpect.TIMEOUT,'$'])
child.close()

在解释器上逐行执行时也一样。一切都很顺利。它按预期生成id_rsa.pub文件。

尝试了几次,但仍然无法弄清楚原因。 我添加了:

child.delaybeforesend=5

仅确保密钥生成正在完成。 请帮忙。

以下是参考命令提示符:

[tecmint@tecmint.com ~]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/tecmint/.ssh/id_rsa): [Pressenter 
key]
Created directory '/home/tecmint/.ssh'.
Enter passphrase (empty for no passphrase): [Press enter key]
Enter same passphrase again: [Press enter key]
Your identification has been saved in /home/tecmint/.ssh/id_rsa.
Your public key has been saved in /home/tecmint/.ssh/id_rsa.pub.
The key fingerprint is:
5f:ad:40:00:8a:d1:9b:99:b3:b0:f8:08:99:c3:ed:d3 tecmint@tecmint.com
The key's randomart image is:

根据我的背景:

.ssh文件夹为空或包含" known_hosts"我运行代码片段时的文件。

当我在解释器上逐行运行相同的代码时,会生成id_rsa和id_rsa.pub

1 个答案:

答案 0 :(得分:0)

你没有等待ssh-keygen发送的提示,所以pexpect不知道发送密码。调整你的提示。