我有一个带有两个按钮的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 变量,它是一个布尔的volatile变量,我们在点击停止按钮时将其设置为false。所以我的问题是当用户点击停止按钮和会话断开连接的频道时, zgrep 表达式继续在服务器上运行。我认为channel.disconnect()应该停止我在服务器上运行的所有命令,有人可以建议如何解决这个问题。感谢。
答案 0 :(得分:3)
@dic19让我知道在断开频道和会话之前向服务器发送 我在JSch邮件列表中找到this post,帮助我解决了我的问题。 因此,要发送Ctrl+C
命令,以便在服务器端中断zgrep
命令执行。< / p>
Ctrl+C
命令,您应该为通道对象((ChannelExec)channel).setPty(true);
启用putty模式,并将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);}
}
答案 1 :(得分:0)
除了将pty设置为true之外,您还可以简单地使用:
<textarea id="x"></textarea>
即使您已经调用了((ChannelExec) channel).sendSignal("INT"); // may throw Exception
(与正在运行的命令的out.close();
相关),此方法仍然有效。