SSH from Java

I’ve not been updating this blog lately but most of my time is consumed at work trying to stop inevitable which eventually happens, I came to this conclusion that the normal state of any complex computer system is not to function properly and we twist its neck and do all the voodoo magic we can to prevent that.

This entry is about SSH, the support engineers most used and least appreciated tool, I had this tedious and boring task that I had to do over and over again, so I decided to automate it using java, using a simple java client that connects to a server and then uses SSH to push all sorts of commands and reads their output, knowing that this would help me solve many of my problems and generally make my life easier. I started by looking online for a jar I can use and perhaps some pointers on how to write a code that can use SSH with rsa and preferably SCP support, however I was surprised of the lack of such a thing online, at least nothing straight forward and to the point that would save me the hassle of going around my tail in circles trying to figure out an over complicated jar that I’d only use a tiny portion of its features.

After hours of search I finally came to jta (, and I’m including a small example of how you can use it to ssh send a command and read its output.

First you need to add jta.jar to your libraries, I included a simple code to execute “ls -ltr” and get its output and return it, ENJOY…..

import de.mud.ssh.SshWrapper;

public String get_ls(String MSISDN)
de.mud.ssh.SshWrapper sw=new SshWrapper();
sw.connect(“”, 22);
sw.login(“user”, “pass”);

byte[] buf=new byte[1024];
ArrayList lines=new ArrayList();
sw.waitfor(“Last login:”);

Thread.sleep(10000);//not needed but you should use it to make sure you dont send commands before the system is ready

sw.send(“ls -ltr”);
String tmpStr=””;
String[] tmpStrArr;
sw.waitfor(“ls”); //blocks to continue
while (true)//to read output
//     System.out.println(sw.send(“findedr “+ MSISDN));
sw.send(“findedr “+ MSISDN);//+ ” > ~/tempEDR.txt  “);
String tmpStr=””;
String[] tmpStrArr;
while (true)

if(<0)///skip empty lines
tmpStr=new String(buf);
tmpStrArr=tmpStr.split(“\n”);//break lines into an array
for(int i=0 ; i<tmpStrArr.length; i++)
lines.add(tmpStrArr[i]);///add lines into array list
}catch (Exception em)

return null;


Leave a Reply

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

You are commenting using your 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