4

我是 JSch 的新手,我的一些脚本有问题,我尝试远程执行并且似乎永远不会结束(并且与使用 putty 运行它时做的事情不同)。

我已将错误和输出流重定向到我的 System.out,并且在执行脚本但脚本完成时确实看到了错误!因此我不明白为什么通道仍然打开(isClosed 和 isEOF 是错误的)。

当我在使用 putty 连接 SSH 时运行命令时,脚本会正确执行并且不会显示任何错误。当我在 Ubuntu 中使用 ssh 命令执行 ssh user@host "my command" 时,我得到与使用 JSch 时相同的输出(std + err),但 ssh 命令不会挂起!

你知道我做错了什么吗,为什么我有不同的输出/行为?这是我运行的 java 代码(顺便说一下,我不能在同一个会话上发送多个具有不同通道的命令,我不知道为什么,因此我为每个 cmd 打开一个会话)。

public static void runCommand(String user, String password, String cmd) throws JSchException, IOException{
    Session session = jSsh.getSession(user, SERVER, SSH_PORT);
    session.setPassword(password);
    session.setConfig(SSH_PROPERTIES);
    session.connect();
    SshCommand sshCmd = new SshCommand(session, cmd);
    runCommand(sshCmd);
    session.disconnect();
}

private static void runCommand(SshCommand sshCmd) throws IOException, JSchException{

    Session session = sshCmd.getSshSession();
    String cmd = sshCmd.getCmd();


    UtilityLogger.log(Level.FINE, "Running command on ssh : "+cmd);

    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setCommand(cmd);
    channel.setInputStream(null);

    InputStream in = channel.getInputStream();
    InputStream err = channel.getErrStream();
    UtilityLogger.log(Level.FINEST, "Connecting to channel");
    channel.connect();
    UtilityLogger.log(Level.FINEST, "Channel connected");

    byte[] tmp = new byte[1024];
            byte[] tmp2 = new byte[1024];
    while (true) {
        //Flush channel
        while (in.available() > 0) {
            int i = in.read(tmp, 0, 1024);
            if (i < 0)
                break;
            UtilityLogger.log(Level.FINE, new String(tmp, 0, i));
        }
        //Flush Error stream
        while (err.available() > 0) {
            int i = err.read(tmp2, 0, 1024);
            if (i < 0)
                break;
            UtilityLogger.log(Level.FINE, new String(tmp2, 0, i));
        }
        if(DONT_WAIT_PROCESS_END)
            break;
        if (channel.isEOF()) {
            UtilityLogger.log(Level.FINE, "Channel exit-status: " + channel.getExitStatus());
            break;
        }
    }
    try{Thread.sleep(TIME_BETWEEN_COMMAND);}catch(Exception ee){}
    channel.disconnect();
    UtilityLogger.log(Level.FINEST, "Channel disconnected");
}
4

2 回答 2

2

尝试附加“退出;” 即使在使用exec频道时,也会在您的命令之后。

于 2013-03-27T22:24:15.190 回答
2

我们的应用程序也没有在 exec 上收到 EOF。将 an 附加exit;到命令并不能解决问题。

它与stderr输出有关。重定向stderr到已stdout解决(解决方法?!)的问题。
所以我们附加2>&1到命令:

${command} 2>&1
于 2019-06-13T16:39:21.007 回答