Android SSH

One of Androids strengths as a platform is that its application framework is based off of the java programming language. Not only did this lower the barrier for developers new to Android, but it brought most of the code that they’d written in java for other platforms with them. There are a vast number of java libraries out there, and many of them can be dropped right into an Android project with no issues or modifications.

A project I recently worked on at Mindgrub required connecting an android application to another machine on the local network running a ssh server. Let’s take a look at what it takes to add this functionality to an Android app.

The first thing you will need to do is grab a copy of JSch. You can download it at http://www.jcraft.com/jsch/ however, the documentation is lacking, and by lacking, I mean there is none. JSch comes with plenty of examples that can get you on your way but, if you’d prefer some javadoc, and don’t mind going back a couple of versions, Paŭlo Ebermann has been kind enough to add documentation: http://epaul.github.com/jsch-documentation/. Another dependency you will need to include is JZlib, also available at jcraft.com.

Once you have the two libraries added to your project you’re ready to get started. Let’s take a look at how to make the initial connection:

String username = "some_username";
String password = "some_password";
String hostname = "some_hostname";
int port = 22;
try{
 JSch sshChannel = new JSch();
 Session session = sshChannel.getSession(userame, hostname, port);
 session.setPassword(password);
 session.setConfig("StrictHostKeyChecking", "no");
 session.connect(timeout);
} catch(JSchException e){
 //error handling
} 

In the above snippet, we create the JSch instance, configure it and connect a session. Obviously this is just an example, so you’ll want to throw this into an AsyncTask or use some other means to make the connection on a background thread. Once you’re connected, you can create a channel:

ChannelExec channel = (ChannelExec)session.openChannel("exec");
channel.setCommand("ls");
channel.connect();

InputStream input = channel.getInputStream();
int data = input.read();
while(data != -1) {
 outputBuffer.append((char)data);
 data = input.read();
}

channel.disconnect(); 

To create the channel, we call openChannel on our session object, passing the type of channel we would like to open as a parameter. These values are strings which correspond to a subclass of Channel. In this case, we specify “exec” to get a ChannelExec object. Specifying “sftp” would return an instance of ChannelSftp. For a complete list of options, see the Channel class.
Again, for simplicity we are just issuing the ‘ls’ command and reading the response back into a StringBuffer. You can issue any command you’d like here. For some more complex examples, such as issuing an scp command to copy a file, check out the examples directory included with JSch.

New Call-to-action