2015-01-21 163 views
1

我使用SSHJ和ExpectIt向託管在Amazon EC2上的虛擬機發送多個命令。我沒有得到任何錯誤,但ExpectIt只執行第一個命令並忘記了其餘部分。你能找出我在這裏做錯了什麼嗎?SSHJ + ExpectIt:無法發送多個命令

{ 
SSHClient ssh=new SSHClient(); 
Session session; 
Shell shell; 
session=ssh.startSession(); 
session.allocateDefaultPTY(); 
shell=session.startShell(); 
Expect expect = new ExpectBuilder() 
     .withOutput(shell.getOutputStream()) 
     .withInputs(shell.getInputStream(), shell.getErrorStream()) 
     .build(); 
expect.sendLine("sudo useradd "+uname+" -g sftponly -m -d /home/"+uname); //Only this command is getting executed 
expect.sendLine("sudo passwd "+uname); 
expect.sendLine(pwd); 
statusbar.setText("Assigning access key to user..."); 
expect.sendLine("sudo mkdir /home/"+uname+"/.ssh"); 
expect.sendLine("sudo touch /home/"+uname+"/.ssh/authorized_keys"); 
expect.sendLine("sudo echo "+pemfile+">/home/"+uname+"/.ssh/authorized_keys"); 
statusbar.setText("Providing permissions to user..."); 
expect.sendLine("sudo chown root /home/"+uname); 
expect.sendLine("sudo chmod go-w /home/"+uname); 
expect.sendLine("sudo mkdir /home/"+uname+"/"+uname); 
expect.sendLine("sudo chmod ug+rwX /home/"+uname); 
expect.sendLine("sudo chmod 700 /home/"+uname+"/.ssh"); 
expect.sendLine("sudo chmod 600 /home/"+uname+"/.ssh/authorized_keys"); 
expect.sendLine("sudo chmod 755 /home/"+uname); 
statusicon.setForeground(Color.green); 
statusbar.setText("User created!"); 
expect.close(); 
} 

注意:有些敏感(但不相關的這個問題)代碼已經從該代碼省略。

回答

1

在發送下一個命令之前,您應等待服務器處理命令。這是因爲您與之通信的遠程外殼,同步執行命令。

Expect.sendLine方法是如此之快,以至於它在第一個命令完成之前傳輸數據。

我建議您在每個sendLine之後添加Expect.expect(PROMPT)方法調用以接收a shell prompt以確保完成上述命令。

看看例子從ExpectIt主頁:

+0

謝謝,但問題是,該系統不給書面命令的任何迴應即。這些命令在沒有任何提示的情況下執行,如「用戶創建」,「密碼設置」或任何其他提示。那麼如何使它能夠期待一個什麼都不能提供的提示呢? – 2015-02-01 07:49:50

+0

命令完成後,遠程shell將在交互模式下運行時顯示提示。這就是session.allocateDefaultPTY()調用假設要做的事情。如果它不起作用,或許你可以嘗試調用session.allocatePTY(...)。看看這個答案:http://stackoverflow.com/questions/3395754/java-and-ssh-maintaining-a-connection – 2015-02-01 08:37:29