2017-04-02 137 views
1

我是新來的,我無法找到我的問題的完整答案。所以我在這裏問。 我正在使用python和pexpect模塊連接到ssh服務器並運行一些命令。但是有些命令不起作用。我看了看文件,我可以看到,運行如下命令:Python模塊pexpect - 如何連接到SSH服務器,然後運行bash命令

ls -l | grep -i <Filter>

因爲我必須使用產卵命令與

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

但是運行bash腳本,我連接到服務器的方式是通過發送帶密鑰的ssh命令:

p = pexpect.spawn("ssh -t -t [email protected] -i ~/.ssh/Keyfile ")

所以我不能運行帶有bash命令的spawn命令(或者我可以嗎?)

響應應該是密碼請求,因爲它將其重定向到另一臺機器。

如何使用spawn命令,以便我可以使用鍵連接到服務器,然後輸入重定向機器的密碼,然後運行bash命令。

注:我試圖找出bash部分。連接到服務器和重定向+密碼插入已經適用於我。

回答

1

您可以在下一行發送命令:

ssh = pexpect.spawn('ssh -t -t [email protected] -i ~/.ssh/Keyfile') 
#You may write expect here to check if the ask if for password or some other error or the initial banner message 
ssh.sendline('password') 
#You may check if the password is successful 
ssh.sendline('/bin/bash -c "ls -l | grep LOG > logs.txt"'); 
+0

謝謝,我不知道爲什麼這種明顯的解決方案並沒有來找我:) 另外請注意,我想這在Android設備上過哪裏有no/bin/bash而是bin/sh 我不得不聲明bin位於系統中,因此結果將是 ** ssh.sendline('system/bin/sh -c「ls -l | grep LOG> logs.txt 「'); ** 如果有人感興趣 – Steven

相關問題