Question

I am trying to run a command on a remote Linux box from Java using JSch (SSH) API. The value of exitStatus is -1 i.e.

int exitStatus = channelExec.getExitStatus()

What is the possible reason to get a negative value?

Was it helpful?

Solution

Note the documentation on getExitStatus().

The exit status will be -1 until the channel is closed.

OTHER TIPS

API Description

Here is my code. It works fine.

public static Result sendCommand(String ip, Integer port, String userName, String password, String cmd) {
    Session session = null;
    ChannelExec channel = null;
    Result result = null;
    try {
        JSch jsch = new JSch();
        JSch.setConfig("StrictHostKeyChecking", "no");

        session = jsch.getSession(userName, ip, port);
        session.setPassword(password);
        session.connect();   

        channel = (ChannelExec)session.openChannel("exec");
        InputStream in = channel.getInputStream();
        channel.setErrStream(System.err);
        channel.setCommand(cmd);
        channel.connect();

        StringBuilder message = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = reader.readLine()) != null)
        {
            message.append(line).append("\n");
        }
        channel.disconnect();
        while (!channel.isClosed()) {

        }
        result = new Result(channel.getExitStatus(),message.toString());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null) {
            try {
                session.disconnect();
            } catch (Exception e) {

            }
        }
    }
    return result;
}

'-1' means that the exit status code has not been received yet from the remote sshd.

channelName.getExitStatus()

it will retrieve the exit status of the remote command corresponding to your channel. If the command is not yet terminated (or this channel type has no command), it will return the status as -1.

For more got to jsch documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top