2014-10-16 150 views
1

我有兩個按鈕用於運行和停止執行JSch命令的swing應用程序。 所以我接下來的一個調用,當我們點擊啓動按鈕方法:執行JSch中斷命令

public String executeSSHCommand(String pattern, String listFiles) {    
    searchRez = new StringBuilder();   
    BufferedReader br = null; 
    String line, cmd = null; 
    // adding ' symbol to pattern 
    pattern = "'"+pattern+"'";  
    // 
    try { 
     Channel channel = session.openChannel("exec");    
     cmd = "zgrep " + pattern + " " + listFiles; 
     log.debug("Executing next ssh command: " + cmd);       
     ((ChannelExec)channel).setCommand(cmd);       
     channel.setInputStream(null); 
     ((ChannelExec)channel).setErrStream(System.err);    
     InputStream in=channel.getInputStream(); 
     channel.connect(); 
     // read server output 
     br = new BufferedReader(new InputStreamReader(in)); 
     while(true && !isCancel){    
      while ((line = br.readLine()) != null && !isCancel) {       
      searchRez.append(line+"\n");       
      }       
      if(channel.isClosed()){ 
       log.debug("Exit status for execute ssh command is " + channel.getExitStatus());     
      break; 
      } 
      try{Thread.sleep(1000);}catch(Exception ee){log.error(ee);} 
     } 

     if (isCancel) { 
      log.debug("Search was canceled by user... ");     

      channel.setInputStream(null);     
      if (in != null) { 
       in.close(); 
       in = null; 
      } 
      if (br != null) { 
       br.close(); 
       br = null; 
      } 
      try{Thread.sleep(1000);}catch(Exception ee){log.error(ee);} 
     } 
     // 
     channel.disconnect(); 
     session.disconnect();   
     log.debug("Search pattern in log file is complete."); 
    } catch (Exception ex) { 
     log.error(ex); 
    }    
    log.debug("Rezult string has next value: " + searchRez.toString()); 
    return searchRez.toString(); 
} 

正如你可以在上面看到,我們有isCancel變量,這是我們設置爲false布爾volatile變量時,點擊停止按鈕。所以我的問題是當用戶點擊停止按鈕和通道與會話斷開連接時,zgrep表達式繼續在服務器上工作。我認爲channel.disconnect()應該停止服務器上的所有運行命令,請有人建議如何解決這個問題。謝謝。

回答

2

@dic19給了我一個想法,發送Ctrl+C命令服務器之前以中斷在服務器端zgrep命令執行斷開通道和會話。

我在JSch郵件列表中找到了this post,這幫助我解決了我的問題。

因此,要發送Ctrl+C命令你應該讓膩子模式通道對象((ChannelExec)channel).setPty(true);3值到通道的OutputStream:

 ((ChannelExec)channel).setPty(true); 
     ((ChannelExec)channel).setCommand(cmd);       
     channel.setInputStream(null); 
     ((ChannelExec)channel).setErrStream(System.err);    
     InputStream in=channel.getInputStream(); 
     OutputStream out = channel.getOutputStream(); 
     channel.connect(); 
     ........... 
     if (isCancel) { 
      log.debug("Search was canceled by user... ");     

      channel.setInputStream(null);     
      if (in != null) { 
       in.close(); 
       in = null; 
      } 
      if (br != null) { 
       br.close(); 
       br = null; 
      } 
      out.write(3); 
      out.flush(); 
      try{Thread.sleep(1000);}catch(Exception ee){log.error(ee);} 
     } 
+2

+1但是請補充說明解決您的問題的代碼,所以萬一鏈接放棄你的答案仍然完整。除此之外,未來的訪問者不需要導航到外部來源就可以找到答案。 – dic19 2014-10-16 13:19:31