关于使用jsch来调用ssh命令启动weblogic,网络流如何终止

sinat_30026967 2016-11-13 09:01:26
如下代码中reader.readLine()是阻塞模式的,这样一但是启动weblogic这种持续输出的ssh命令,造成程序一直阻塞在readLine(),有想过使用read()去读,但是情况应该也是一样,因为无法确定该流的结尾标记,有没有什么方法可以让其如果阻塞5秒直接退出这个循环
public static String exec(String host,String user,String psw,int port,String command){
String result="";
Session session =null;
ChannelExec openChannel =null;
String buf="";
try {
JSch jsch=new JSch();
session = jsch.getSession(user, host, port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword(psw);
session.connect();
//session.setTimeout(1000);
openChannel = (ChannelExec) session.openChannel("exec");
openChannel.setCommand(command);
//int exitStatus = openChannel.getExitStatus();
//System.out.println(exitStatus);

openChannel.connect(500);
InputStream in = openChannel.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
buf = null;
while ((buf = reader.readLine()) != null) {
result+= new String(buf.getBytes("gbk"),"UTF-8"); //+"\r\n"
System.out.println(buf);
}
System.out.println(buf);
in.close();
} catch (JSchException e ) {
result+=e.getMessage();
}catch(IOException e){
result+=e.getMessage();
}finally{
if(openChannel!=null&&!openChannel.isClosed()){
openChannel.disconnect();
}
if(session!=null&&session.isConnected()){
session.disconnect();
}
}
return result;
}
...全文
207 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧