Category Archives: Java

java tips

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”;

}