我有 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 变量,它是 boolean 型 volatile 变量,当单击停止按钮时我们将其设置为 false。所以我的问题是,当用户单击停止按钮并且 session channel 断开连接时,zgrep表达式继续在服务器上工作。我认为channel.disconnect()应该停止我在服务器上运行的所有命令,有人可以建议如何解决这个问题。谢谢。
最佳答案
@dic19给了我一个想法,在断开 channel 和 session 之前向服务器发送 Ctrl+C 命令,以中断服务器端的 zgrep 命令执行。
我找到了this post在 JSch 邮件列表中,它帮助我解决了我的问题。
因此,要发送 Ctrl+C
命令,您应该为 channel 对象启用 putty 模式 ((ChannelExec)channel).setPty(true);
并写入 3
channel 输出流的值:
((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);}
}
关于java - JSch 中断命令执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26403422/