2015-10-23 26 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)