Vivek Vivek - 4 months ago 16
Java Question

Libraries to run unix commands from Java

I am looking for libraries that I can use to send Unix commands from my Java code. I have already tried Expect4J and Gaynmed, but could not find good documentation with them. My requirements include:


  1. Running multiple commands.

  2. Capture output for previous command.

  3. Take some action/Run different command based on output of last command.



Any pointers will be appreciated.

Answer

Looking at the names of the libraries you mentioned, it seems like you want to run the commands on a remote server using ssh.

Check out http://code.google.com/p/sshxcute/

Code is pretty easy

// Initialize a ConnBean object, parameter list is ip, username, password
ConnBean cb = new ConnBean("ip ", "username","password");
// Put the ConnBean instance as parameter for SSHExec static method getInstance(ConnBean) to retrieve a singleton SSHExec instance
ssh = SSHExec.getInstance(cb);          
// Connect to server
ssh.connect();
CustomTask sampleTask = new ExecCommand("echo 123");
ssh.exec(sampleTask);

Getting the output is easy too. Just check the link I provided.

Result res = ssh.exec(task); 
if (res.isSuccess) {
    System.out.println("Return code: " + res.rc);
    System.out.println("sysout: " + res.sysout);
} else {
    System.out.println("Return code: " + res.rc);
    System.out.println("error message: " + res.error_msg);
}
Comments