Question

I'm trying to use jsch to get the output of commands send hrough SSH. My problem is that I need to get the result of the command into a String in order to use it later. For exemple if I send the command "ls" I want the name of the files in the folder in a string.

How can I do that ?

Here is my code :

import com.jcraft.jsch.*;


public class SSHCommand2 {
public static void main(String[] args) {
    String host="host";
    String user="user";
    String password="password";


    try{


        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        JSch jsch = new JSch();
        Session session=jsch.getSession(user, host, 22);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();
        System.out.println("Connected");

        Channel channel = session.openChannel("shell");
        ((ChannelShell) channel).setPty(true);

        OutputStream inputstream_for_the_channel = channel.getOutputStream();
        PrintStream commander = new PrintStream(inputstream_for_the_channel, true);
        channel.setOutputStream(System.out, true);

        channel.connect();
        commander.println("ls");

        if(channel.isClosed()){
            //if(in.available()>0) continue;
            System.out.println("exit-status: "+channel.getExitStatus());
            //break;
          }
        do {
            Thread.sleep(1000);
        } while(!channel.isEOF());
        session.disconnect();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
Was it helpful?

Solution

this is how I read the output of my command

Edit

1) Method to Connect to the server:

public void connect (final String host){
    if(host.isEmpty())
        return;

    hostname = host;
    try{
        JSch jsch=new JSch();
        String user ="yourUserName";
        String host = "yourHost";

        Session myLocalSession=jsch.getSession(user, host, 22);
        //myLocalSession=jsch.getSession(user, "192.168.1.104", 22);

        myLocalSession.setPassword("yourPassword");

        myLocalSession.setConfig("StrictHostKeyChecking", "no");

        myLocalSession.connect(5000);   // making a connection with timeout.
        myChannel = myLocalSession.openChannel("shell");

        InputStream inStream = myChannel.getInputStream();

        OutputStream outStream = myChannel.getOutputStream();
        toChannel = new PrintWriter(new OutputStreamWriter(outStream), true);

        myChannel.connect();
        readerThread(new InputStreamReader(inStream));


        Thread.sleep(100);
        sendCommand("cd "+path);
      }
    catch(JSchException e){
        String message = e.getMessage();
        if(message.contains("UnknownHostException"))
            myParser.print(">>>>> Unknow Host. Please verify hostname.");
        else if(message.contains("socket is not established"))
            myParser.print(">>>>> Can't connect to the server for the moment.");
        else if(message.contains("Auth fail"))
            myParser.print(">>>>> Please verify login and password");
        else if(message.contains("Connection refused"))
            myParser.print(">>>>> The server refused the connection");
        else
            System.out.println("*******Unknown ERROR********");

        System.out.println(e.getMessage());
        System.out.println(e + "****connect()");
      }
    catch(IOException e)
    {
        System.out.println(e);
        myParser.print(">>>>> Error when reading data streams from the server");
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

2) Method to send a command to the server

public void sendCommand(final String command)
{
    if(myLocalSession != null && myLocalSession.isConnected())
    {
        try {
            toChannel.println(command);
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

3) Thread method that read answer from the server

void readerThread(final InputStreamReader tout)
{
    Thread read2 = new Thread(){
    @Override
    public void run(){
        StringBuilder line = new StringBuilder();
        char toAppend = ' ';
        try {
            while(true){
                try {
                    while (tout.ready()) {
                        toAppend = (char) tout.read();
                        if(toAppend == '\n')
                        {
                            System.out.print(line.toString());
                            line.setLength(0);
                        }
                        else
                            line.append(toAppend);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("\n\n\n************errorrrrrrr reading character**********\n\n\n");
                }
                Thread.sleep(1000);
            }
        }catch (Exception ex) {
            System.out.println(ex);
            try{
                tout.close();
            }
            catch(Exception e)
            {}
        }
    }
    };
    read2.start();
}

You can use a bufferedReader with the InputStreamReader and read line by line. I use an infinite loop and pause for one second after each failed attempt to read (nothing from the server).

Let's say that the three method are in SessionB class. Example:

SessionB testConnexion = new SessionB();
testConnexion.connect();
testConnexion.sendCommand("cd myFolder");
testConnexion.sendCommand("ls");

You should get the list of file in your console.

If you need, to be able to interact (send a command depending of the output), check my post here.

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