2014-04-04 81 views
0

我想連接一個Linux服務器並執行命令,但是當我發送命令shsu - 它需要密碼,但是我的程序在它提出要求之前發送密碼。我怎麼解決這個問題?java jsch su-root

public class Stream 
{ 
    public void getStream(String fileName) 
    { 
     String user = usernametext.getText(); 
     String host = hostiptext.getText(); 
     String password = pass.getText(); 
     String command4 = "sh\nsu -\nmypassword\n"; 
     try 
     { 
      System.out.println("preparing the host information for stream."); 
      JSch jsch = new JSch(); 
      Session session = jsch.getSession(user, host, 22); 
      session.setPassword(password); 
      session.setConfig("StrictHostKeyChecking", "no"); 
      session.connect(10 * 1000); 
      Channel channel = session.openChannel("shell"); 
      InputStream is = new ByteArrayInputStream(command4.getBytes()); 
      channel.setInputStream(is); 
      channel.setOutputStream(System.out); 
      channel.connect(15 * 1000); 
      session.connect(10 * 10); 
      channel.disconnect(); 
      session.disconnect(); 
     } 
     catch (Exception ex) 
     { 
      System.out.println("Exception found while streaming."); 
     } 
    } 

} 

回答

0

由於您使用的是通道爲什麼你需要調用另一個SH?

上述任何一種方法都是通過單個命令,然後讀取inputStream,直到返回提示符,然後可以設置下一個輸入,例如密碼或什麼。

僞代碼是

write "su -" 
readUntil "password:" 
write "******" 
readUntil prompt 
etc. 
+0

我是新來的Java不知道如何做到這一點 – RecreatioN

+0

基本上你正在閱讀和對輸入和輸出流寫。見http://stackoverflow.com/questions/4194439/sending-commands-to-server-via-jsch-shell-channel –

+0

你有這個解決方案,請張貼在這裏。我試圖執行「su」命令,然後在下一行輸入root密碼,我得到的錯誤是「標準必須是tty」。我想要的只是在Java中使用java進入root。 – thomson