python:使用Popen与shell命令交互

2024-09-28 01:25:41 发布

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

我需要使用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

如果我运行这个程序,它仍然会提示并请求输入。如何自动响应提示?谢谢。在


Tags: key程序cmd机器outputdnsstdinprivate
2条回答

系统会提示您将主机密钥添加到know hosts文件中,因为ssh配置为StrictHostKeyChecking。从手册页:

StrictHostKeyChecking

If this flag is set to “yes”, ssh(1) will never automatically add host keys to the ~/.ssh/known_hosts file, and refuses to connect to hosts whose host key has changed. This provides maximum protection against trojan horse attacks, though it can be annoying when the /etc/ssh/ssh_known_hosts file is poorly maintained or when connections to new hosts are frequently made. This option forces the user to manually add all new hosts. If this flag is set to “no”, ssh will automatically add new host keys to the user known hosts files. If this flag is set to “ask”, new host keys will be added to the user known host files only after the user has confirmed that is what they really want to do, and ssh will

如果您希望ssh/scp在不提示的情况下自动接受新密钥,可以将StrictHostKeyChecking设置为“no”。在命令行上:

scp -o StrictHostKeyChecking=no ...

也可以启用批处理模式:

BatchMode

If set to “yes”, passphrase/password querying will be disabled. This option is useful in scripts and other batch jobs where no user is present to supply the password. The argument must be “yes” or “no”. The default is “no”.

使用BatchMode=yes,ssh/scp将失败而不是提示(这通常是对脚本的改进)。在

我知道避免被问及指纹匹配的最佳方法是在.ssh/known_hosts中预先填充相关的密钥。在大多数情况下,您确实应该已经知道远程计算机的公钥是什么,而且将它们放在ssh可以找到的known_hosts中是很简单的。在

在少数情况下,您不知道,也不可能知道远程公钥,那么最正确的解决方案取决于您不知道的原因。例如,如果您正在编写的软件需要在任意用户框上运行,并且可能需要代表用户通过ssh将其发送到其他任意的框中,那么您的软件最好自行运行ssh-keyscan来获取表面上的远程公钥,如果可能的话,让用户显式地批准或拒绝它,如果被批准,则将密钥附加到已知的主机,然后调用ssh。在

相关问题 更多 >

    热门问题