我需要使用python执行几个shell命令,但是我无法解决其中一个问题。当我scp到另一台机器时,它通常会提示并询问是否将此机器添加到已知主机。我想让程序自动输入“是”,但我不能让它工作。到目前为止,我的计划是这样的:
from subprocess import Popen, PIPE, STDOUT
def auto():
user = "abc"
inst_dns = "example.com"
private_key = "sample.sem"
capFile = "/home/ubuntu/*.cap"
temp = "%s@%s:~" %(user, inst_dns)
scp_cmd = ["scp", "-i", private_key, capFile, temp]
print ( "The scp command is: %s" %" ".join(scp_cmd) )
scpExec = Popen(scp_cmd, shell=False, stdin=PIPE, stdout=PIPE)
# this is the place I tried to write "yes"
# but doesn't work
scpExec.stdin.write("yes\n")
scpExec.stdin.flush()
while True:
output = scpExec.stdout.readline()
print ("output: %s" %output)
if output == "":
break
如果我运行这个程序,它仍然会提示并请求输入。如何自动响应提示?谢谢。在
系统会提示您将主机密钥添加到know hosts文件中,因为ssh配置为
StrictHostKeyChecking
。从手册页:如果您希望ssh/scp在不提示的情况下自动接受新密钥,可以将
StrictHostKeyChecking
设置为“no”。在命令行上:也可以启用批处理模式:
使用
BatchMode=yes
,ssh/scp将失败而不是提示(这通常是对脚本的改进)。在我知道避免被问及指纹匹配的最佳方法是在
.ssh/known_hosts
中预先填充相关的密钥。在大多数情况下,您确实应该已经知道远程计算机的公钥是什么,而且将它们放在ssh可以找到的known_hosts
中是很简单的。在在少数情况下,您不知道,也不可能知道远程公钥,那么最正确的解决方案取决于您不知道的原因。例如,如果您正在编写的软件需要在任意用户框上运行,并且可能需要代表用户通过ssh将其发送到其他任意的框中,那么您的软件最好自行运行
ssh-keyscan
来获取表面上的远程公钥,如果可能的话,让用户显式地批准或拒绝它,如果被批准,则将密钥附加到已知的主机,然后调用ssh。在相关问题 更多 >
编程相关推荐