2016-08-11 70 views
0

我試圖在使用JSch的java中獲取shell腳本的輸出。執行sudo管理命令並獲取腳本的輸出。僅在JSch shell通道中獲取特定命令的輸出

Properties prop = new Properties(); 
InputStream input = null; 

String host="myhost"; 
StringBuilder command1= new StringBuilder(); 
String userName = "root"; 
String password="password"; 

try{ 

    JSch jsch = new JSch(); 
    Session session = jsch.getSession(userName, host, 22); 

    session.setPassword(password); 
    session.connect(); 
    System.out.println("Connected"); 

    List<String> commands = new ArrayList<String>(); 
    commands.add("ls"); 
    commands.add("sudo myadmincmd"); 
    commands.add("cd /logs"); 
    commands.add("my script..."); 
    Channel channel = session.openChannel("shell"); 
    channel.connect(); 
    channel.setOutputStream(System.out); 

    OutputStream os = channel.getOutputStream(); 
    PrintStream shell = new PrintStream(os, true); 

    for (String cmd : commands) { 
     shell.println(cmd); 
     try { 
      Thread.sleep(2000); 
     } 
     catch (Exception ee) { 
     } 
    } 
    shell.println("exit"); 
    shell.close(); 

    channel.disconnect(); 
    session.disconnect(); 

}catch(Exception e){ 
    e.printStackTrace(); 
} 

輸出:

*ADMINSHELL* :/home/abcd # cd /logs 
*ADMINSHELL* :/logs # 
*ADMINSHELL* :/logs # my script... 
.... 
output goes here... 
.... 

我怎樣才能得到只有這ADMINSHELL的輸出?例如,我只需要最終輸出。我試着用下面的支票,

for (String cmd : commands) { 
    if(cmd.startsWith("for script")){ 
     shell.println(cmd); 
    } 

    try { 
     Thread.sleep(2000); 
    } 
    catch (Exception e) { 
    } 
} 

但是這次我得到了一些權限被拒絕的問題。我只需要最後腳本的輸出。

.... 
output goes here... 
.... 

回答

1

您必須將輸出讀取到某個緩衝區/字符串。然後解析出來,只打印你想要的部分。

請參閱How to get jsch shell command output in String

沒有其他方法可以將單個命令的輸出分開。從SSH客戶端角度來看,shell只是一個帶有輸入/輸出的黑盒子。沒有結構。


有幫助,當你之前和喜歡的劇本後,打印一些分隔符:

echo ---begin--- 
/.../myscript.sh 
echo ---end--- 
相關問題