2015-10-23 28 views
0

我需要在Python执行这个命令,并从键盘输入密码,这是作品:如何命令传递命令pexpext在python

import os 
cmd = "cat /home/user1/.ssh/id_rsa.pub | ssh [email protected] \'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 [email protected] 
/bin/cat: |: No such file or directory 
/bin/cat: ssh: No such file or directory 
/bin/cat: [email protected]: 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. 将stdin注入/写入passwd作为假用户,但是如何!
+0

无关的:没有必要逃避双引号内的单引号在Python:“ ”_ '|' _“' – jfs

+0

你有没有考虑'ssh-copy-id'呢? – jfs

+0

@ J.F.Sebastian Nope,不可用。 – emcek

回答

1

the pexpect docs

记住Pexpect的不解释shell元字符,如 重定向,管道或通配符(>|,或*)。这是一个 常见的错误。如果你想运行一个命令并通过 管道,那么你还必须启动一个shell。例如::

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

谢谢,就是这样! – emcek

0

为我工作:

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