我正在开发一个项目,使用JSch在远程服务器的屏幕上重新启动某些东西......但是我遇到了一个问题。它会在100%的时间内发送前2个命令,但第3个命令只会在某些时间发送。任何帮助将不胜感激。
public static void stopServer(String name, String ip, String passwd)
{
try {
Session session = Main.jsch.getSession("user",ip,22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(passwd);
session.connect();
Channel channel = session.openChannel("shell");
channel.connect();
ChannelShell cs = (ChannelShell) channel;
cs.setPty(true);
DataInputStream dataIn = new DataInputStream(channel.getInputStream());
PrintStream dataOut = new PrintStream(channel.getOutputStream());
dataOut.println("screen -x "+name);
dataOut.flush();
dataOut.println("stop");
dataOut.flush();
String line = dataIn.readLine();
System.out.println(line);
while(true) {
line = dataIn.readLine();
System.out.println(line);
if(line.contains("\"quit\""))
{
break;
}
}
TimeUnit.SECONDS.sleep(1);
dataOut.println("quit");
dataOut.flush();
System.out.println("Shutdown");
dataIn.close();
dataOut.close();
channel.disconnect();
session.disconnect();
}catch(Exception e)
{
e.printStackTrace();
}
}
这会从我看到的内容中100%发送屏幕-x'名称'和停止,但'quit'命令实际上只有控制台发送/理解了一小部分时间。任何帮助将不胜感激!!
答案 0 :(得分:2)
我设法以不使用shell通道的方式修复此问题,但它足够可靠,可以正常工作:
//Start EXEC
ChannelExec ce = (ChannelExec) session.openChannel("exec");
ce.setCommand("screen -S " + name + " -X stuff 'quit\n'");
ce.setInputStream(null);
ce.setErrStream(System.err);
InputStream in=ce.getInputStream();
ce.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
//System.out.print(new String(tmp, 0, i));
}
if(ce.isClosed()){
if(in.available()>0) continue;
//System.out.println("exit-status: "+ce.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
ce.disconnect();
//STOP EXEC
尽管这并没有解决问题的原始方面,但它为我解决了这个问题。
答案 1 :(得分:0)
如果在发送“quit”命令之前某个时间抛出异常,则quit命令将永远不会被发送。
如果while循环永不中断,则会阻止“退出” 命令也被发送。