【发布时间】:2020-01-05 18:49:27
【问题描述】:
我有两个用于运行和停止执行 JSch 命令的按钮的 Swing 应用程序。 所以我有下一个方法,当我们点击开始按钮时会调用它:
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 变量,它是布尔型 volatile 变量,我们在单击停止按钮时将其设置为 false。所以我的问题是当用户单击停止按钮并且会话通道断开连接时,zgrep 表达式继续在服务器上工作。我认为 channel.disconnect() 应该停止我在服务器上运行的所有命令,有人可以建议如何解决这个问题。谢谢。
【问题讨论】: