我需要在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
我看到了兩個解決方案:
- 修復pexpect的命令,它將整個字符串識別爲一個命令,或者,
- 將stdin注入/寫入passwd作爲假用戶,但是如何!
無關的:沒有必要逃避雙引號內的單引號在Python:「 」_ '|' _「' – jfs
你有沒有考慮'ssh-copy-id'呢? – jfs
@ J.F.Sebastian Nope,不可用。 – emcek