Jsch error return codes not consistent

2019-04-28 08:37发布

问题:

I am using the nice http://www.jcraft.com/jsch/ library - however when I run some commands, I see that jsch returns a getExitStatus of -1, from time to time, even though the script ran fine (when I run it by hand it is consistently a successful 0 exit code). Any ideas?

(seems to happen to a wide variety of commands)

回答1:

I gave up on Jsch - and its incredibly unhelpful API and switched to:

http://www.cleondris.ch/opensource/ssh2/

(Ganymede SSH2). I do a LOT with ssh in the JVM and over months of 24 hour usage ganymede has proven far more reliable. And more pleasant. My main remaining gripe is around being apparently unable to set timeouts for SCP.



回答2:

I suffered the same issue and then came across this in the Jsch changelog (http://www.jcraft.com/jsch/ChangeLog):

  • feature: added 'Channel.isClosed()'. Channel.getExitStatus() should be invoked after Channel.isClosed()==true.

So knocked this up: Needs to be called before channel.disconnect(), else still get -1 issue:

private static void waitForChannelClosure(ChannelExec ce, long maxwaitMs) {

    log.info("waitForChannelClosure >>>");
    final long until = System.currentTimeMillis() + maxwaitMs;

    try {
        while (!ce.isClosed() && System.currentTimeMillis() < until) { 
            log.info("SFTP channel not closed .. waiting");
            Thread.sleep(250);
        }

    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted", e);
    }

    if (!ce.isClosed()) {
        throw new RuntimeException("Channel not closed in timely manner!");
    }

};


标签: java ssh