Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Libraries to run unix commands from Java

Tags:

java

unix

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.

like image 443
Vivek Avatar asked Dec 04 '22 05:12

Vivek


1 Answers

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);
}
like image 66
Abhijeet Rastogi Avatar answered Dec 19 '22 07:12

Abhijeet Rastogi