如何在命令中将命令传递给python中的pexpext

时间:2015-10-23 15:31:47

标签: linux python-2.7 stdin pexpect

我需要在python中执行此命令并从键盘输入密码,这是有效的:

import os
cmd = "cat /home/user1/.ssh/id_rsa.pub | ssh user2@host.net \'cat >> .ssh/authorized_keys\' > /dev/null 2>&1"
os.system(cmd)

如您所见,我希望通过ssh将公钥附加到远程主机 请参见此处:equivalent-of-ftp-put-and-append-in-scp和此处:copy-and-append-files-to-a-remote-machine-cat-error

当然我希望它在没有用户输入的情况下完成它我尝试了pexpect并且我认为命令对它来说很奇怪:

import pexpect

child = pexpect.spawn(command=cmd, timeout=10, logfile=open('debug.txt', 'a+'))
matched = child.expect(['Password:', pexpect.EOF, pexpect.TIMEOUT])
if matched == 0:
    child.sendline(passwd)

在debug.txt中:

ssh-rsa AAAA..........vcxv233x5v3543sfsfvsv user1@host1
/bin/cat: |: No such file or directory
/bin/cat: ssh: No such file or directory
/bin/cat: user2@host.net: No such file or directory
/bin/cat: cat >> .ssh/authorized_keys: No such file or directory
/bin/cat: >: No such file or directory
/bin/cat: 2>&1: No such file or directory

我看到两个解决方案:

  1. 修复pexpect的命令,它将整个字符串识别为一个命令或
  2. 将passwd作为假用户注入/写入stdin,但是如何!?!?

2 个答案:

答案 0 :(得分:1)

来自the pexpect docs

  

请记住,Pexpect不会解释shell元字符,例如   重定向,管道或外卡(>|*)。这是一个   常见的错误。如果要运行命令并通过它   另一个命令然后你还必须启动一个shell。例如::

child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
child.expect(pexpect.EOF)

答案 1 :(得分:0)

这对我有用:

command = "/bin/bash -c \"cat /home/user1/.ssh/id_rsa.pub | ssh user2@host.net \'cat >> ~/.ssh/authorized_keys\' > /dev/null 2>&1\""
child = spawn(command=command, timeout=5)