how to save in a variable the result of executing an ssh command in java with jsch?

0

I was recently finding out how to execute ssh commands in java programs, and I came across a post recommended by the jsch library. The method that I found was the following:

import java.util.Properties;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session; 

public static void EjecutarSSH(String pUser, String pPass, String pHost, int pPort, String pComando) throws Exception {
    JSch ssh = new JSch();
    // Instancio el objeto session para la transferencia
    Session session = null;
    // instancio el canal sftp
    ChannelExec channelssh = null;
    try {
        // Inciciamos el JSch con el usuario, host y puerto
        session = ssh.getSession(pUser, pHost, pPort);
        // Seteamos el password
        session.setPassword(pPass);
        // El SFTP requiere un intercambio de claves
        // con esta propiedad le decimos que acepte la clave
        // sin pedir confirmación
        Properties prop = new Properties();
        prop.put("StrictHostKeyChecking", "no");
        session.setConfig(prop);
        session.connect();

        // Abrimos el canal de sftp y conectamos
        channelssh = (ChannelExec) session.openChannel("exec");
        // seteamos el comando a ejecutar
        channelssh.setCommand(pComando);
        // conectar y ejecutar
        channelssh.connect();
    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        // Cerramos el canal y session
        if (channelssh.isConnected())
            channelssh.disconnect();
        if (session.isConnected())
            session.disconnect();
    }// end try
}// EjecutarSSH

Now, my problem is: How to collect in a variable the result of the command executed by the method?

For example, if the method executes the command:

(grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} 
END 
{print usage "%"}') 

That the consumption returns in% of the CPU of the PC, and I would like to save in a String the result of the execution of said command so that the method itself returns it, Would the method be modified?

I would greatly appreciate your help. Thanks and regards.

    
asked by Luis Ramiro 09.05.2018 в 17:49
source

1 answer

0

You can do it with this code:

ByteArrayOutputStream baos=new ByteArrayOutputStream();
consola.setOutputStream(baos);
String cadena=new String(baos.toByteArray());

Although this something different from yours because I start the console, like this:

ChannelShell consola = (ChannelShell) sesion.openChannel("shell");

But that's because my goal was to execute commands in my application and run them on the server. But that code can be used to test and adapt it to what you are doing.

    
answered by 09.05.2018 в 18:35