Wednesday, 24 April 2013

Java: How to Execute Unix Command from Java

Unix Commands can be executed from Java using Java ssh2 API.
You can download "ganymed-ssh2-build210.jar" for ssh2 API from following link and add it to the classpath:

http://mirrors.ibiblio.org/pub/mirrors/maven2/ch/ethz/ganymed/ganymed-ssh2/build210/ganymed-ssh2-build210.jar

Following is the Java program for executing Unix Command : 

import java.lang.*;
import java.io.*;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class unix
        {
static String ipaddress , username, password, command;
    unix(String ipaddress,String username,String password,String command)
   {
    unix.ipaddress = ipaddress;
    unix.username =  username;
    unix.password = password ;
    unix.command  = command;
    }
    
       
    public static void main(String args[]) throws IOException
    {
    unix obj = new unix("ipaddress","userid","password","absolute path of command to execute");    
         
    try {
        Connection conn = new Connection(unix.ipaddress);
        conn.connect();
        boolean isauthenticated = conn.authenticateWithPassword(unix.username,unix.password);
        if ( isauthenticated=false)
        {
            System.out.println("Authentication failed");
            System.exit(1);
            
        }
    Session sess = conn.openSession();
    sess.execCommand(unix.command);
    InputStream stdout = new StreamGobbler(sess.getStdout());
    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
    while(true)
    {
        String line =br.readLine();
        if (line==null)
        {
            break;
        }
       System.out.println(line);    
    }
    sess.close();
    conn.close();
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
    }
}

No comments:

Post a Comment