NutzCN Logo
问答 java推送ssh命令,会不会有什么超时的说法?
发布于 3168天前 作者 qq_6427b776 2050 次浏览 复制 上一个帖子 下一个帖子
标签:
/**
 * 执行相关的命令
 */
public String execCmd(String command) throws Exception {
    ChannelExec channelExec = null;
    InputStream in = null;
    StringBuffer buf = null;
    try {
       channelExec = (ChannelExec) session.openChannel("exec");
       channelExec.setCommand(command);
       channelExec.setInputStream(null);
       channelExec.setErrStream(System.err);
       in = channelExec.getInputStream();
       channelExec.connect();
       int res = -1;
       buf = new StringBuffer(1024);
       byte[] tmp = new byte[1024];
       while (true) {
         while (in.available() > 0) {
          int i = in.read(tmp, 0, 1024);
          if (i < 0)
              break;
          buf.append(new String(tmp, 0, i));
         }
         if (channelExec.isClosed()) {
          res = channelExec.getExitStatus();
          System.out.println(format("Exit-status: %d", res));
          break;
         }
       }
    } finally {
       if (channelExec != null) {
         channelExec.disconnect();
         channelExec = null;
       }
       if (in != null) {
         try {
          in.close();
         } catch (IOException e) {
          LOG.debug(e);
         }
         in = null;
       }
    }
    return buf.toString();
}
3 回复

不晓得这代码是干啥。。。。

楼主想执行shell脚本?

说起shell脚本,我一般用apache sshd里面的ssh client去调用,但本质无异.

添加回复
请先登陆
回到顶部