Java program to run SSH commands

Hi,

Recently I was searching about how to be able to execute linux commands from java connecting to remote servers using SSH.

My first approach was trying to wrap a shell script allowing me to skip the password prompt passing it as a parameter to the ssh call… It was not easy to find how to do it. At the end it seems that it is possible using Expect scripts ( http://en.wikipedia.org/wiki/Expect )

But then I found JSch: A java lib which is a pure Java implementation of SSH2. Which is what I was looking for. You can donwload it from http://www.jcraft.com/jsch/

Below you can find my sample piece of code which is mostly copied from: http://www.journaldev.com/246/java-program-to-run-shell-commands-on-ssh-enabled-system

 

public static String cmdExecSSH(String host, String user, String password, String cmd ){

String s = null;

try{

 

java.util.Properties config = new java.util.Properties();

config.put(“StrictHostKeyChecking”, “no”);

JSch jsch = new JSch();

Session session=jsch.getSession(user, host, 22);

session.setPassword(password);

session.setConfig(config);

session.connect();

System.out.println(“Connected “+user+”@”+host);

 

Channel channel=session.openChannel(“exec”);

((ChannelExec)channel).setCommand(cmd);

channel.setInputStream(null);

((ChannelExec)channel).setErrStream(System.err);

 

InputStream in=channel.getInputStream();

channel.connect();

byte[] tmp=new byte[1024];

while(true){

while(in.available()>0){

int i=in.read(tmp, 0, 1024);

if(i<0)break;

String line = new String(tmp, 0, i);

s = (s == null)?line:(s+”\n”+line);

}

if(channel.isClosed())

break;

try{Thread.sleep(1000);}catch(Exception ee){}

}

channel.disconnect();

session.disconnect();

System.out.println(“DONE”);

}catch(Exception e){

e.printStackTrace();

}

return (s != null)?s:”no matches found”;

}

Advertisements

5 thoughts on “Java program to run SSH commands

  1. tomeumir Post author

    I have modified the code for returning the output formatted in the same way that it would be in the remote console. (Because I am executing searches using grep commands in several servers and I wanted the lines as long as in the remote log file whatever is their length)

    public static String cmdExecSSH(String host, String user, String password, String cmd ){

    String s = null;

    try{

    java.util.Properties config = new java.util.Properties();
    config.put(“StrictHostKeyChecking”, “no”);
    JSch jsch = new JSch();
    Session session=jsch.getSession(user, host, 22);
    session.setPassword(password);
    session.setConfig(config);
    session.connect();
    System.out.println(“Connected “+user+”@”+host);

    Channel channel=session.openChannel(“exec”);
    ((ChannelExec)channel).setCommand(cmd);
    //channel.setInputStream(null);
    ((ChannelExec)channel).setErrStream(System.err);

    channel.connect();

    BufferedReader stdInput = new BufferedReader(new
    InputStreamReader(channel.getInputStream()));

    String line = null;
    while ((line = stdInput.readLine()) != null)
    s = (s == null)?line:(s+”\n”+line);

    channel.disconnect();
    session.disconnect();
    System.out.println(“disconnected”);
    }catch(Exception e){
    e.printStackTrace();
    }

    return (s != null)?s:”no matches found”;
    }

    Reply
  2. Nur

    can please share how to run ksh program using this. i am stuck. i want to execute a abc.ksh (arg)program in a particular directory but abc.ksh is in different directory, it returns me abc.ksh not found. I was able to run this manually.

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s