Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason to get exit status value -1 in JSch

Tags:

java

ssh

jsch

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?

like image 577
Saikat Avatar asked Jan 22 '14 10:01

Saikat


3 Answers

Note the documentation on getExitStatus().

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

like image 72
Damienknight Avatar answered Nov 14 '22 22:11

Damienknight


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;
}
like image 23
Xinyuan.Yan Avatar answered Nov 14 '22 23:11

Xinyuan.Yan


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

like image 45
ymnk Avatar answered Nov 14 '22 21:11

ymnk