SSH, execute remote commands with Android

SSH, execute remote commands with Android

We need to download the JSCH libraries and JZLIB libraries that we can get directly on here:

We need to give INTERNET permission to our application in the manifest file.

In this example we execute the command ls in a remote machine using SSH and return the result. NOTE: you should improve the code for exception handling.

<!-- AndroidManifest.xml-->

<manifest ... >
 <uses-permission android:name="android.permission.INTERNET" />
</manifest>
// MyClass.java

public static String executeRemoteCommand(
                       String username,
                       String password,
                       String hostname,
                       int port) throws Exception {     

  JSch jsch = new JSch();
  Session session = jsch.getSession(username, hostname, 22);
  session.setPassword(password);

  // Avoid asking for key confirmation
  Properties prop = new Properties();
  prop.put("StrictHostKeyChecking", "no");
  session.setConfig(prop);

  session.connect();

  // SSH Channel
  ChannelExec channelssh = (ChannelExec) session.openChannel("exec");      
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  channelssh.setOutputStream(baos);

  // Execute command
  channelssh.setCommand("ls");
  channelssh.connect();        
  channelssh.disconnect();

  return baos.toString();
}