使用 Paramiko 自动执行 ssh-keygen

Executing ssh-keygen automatically with Paramiko

我有一个 lxd 容器 master,它有一个 IP 10.154.151.8。我想在我的机器上通过 ssh 对其执行 ssh-keygen。也就是说,

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.154.151.8',username='root')
stdin,stdout,stderr = ssh.exec_command('ssh-keygen')

我在这里面临的问题是,在给出命令 ssh-keygen 后,locationpassphrase (两次)被问到。我通常会做的就是在交互式 shell 中按 enter 三次 。但是在这里,因为我通过 ssh 连接到 master,所以我不能这样做。输出为:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/rohit/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/rohit/.ssh/id_rsa.
Your public key has been saved in /home/rohit/.ssh/id_rsa.pub.
The key fingerprint is:

所以我尝试这样做:

stdin.write("\n")
stdin.write("\n")
stdin.write("\n")

但这并没有创建 id_rsa.pub 文件。

同样我试过:

stdin.write("") 
stdin.write("") 
stdin.write("") 

但这也没有用。

那么,我做错了什么?

此外还有其他方法(最好使用paramiko)来生成id_rsa.pub文件吗?

感谢任何帮助!

不要尝试模拟用户输入。

使用-f and -N command-line switches of ssh-keygen:

ssh-keygen -f keyfile -N ""