我需要在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
我看到两个解决方案:
答案 0 :(得分:1)
请记住,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)