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.