Pozinux Pozinux - 1 year ago 225
Android Question

Simple SSH connect with JSch

I am trying to make something from this simple example :

SSH, execute remote commands with Android

I just want to see if I can connect from my android phone to a linux server using SSH but it doesn't work...

Here is my main code :

package com.example.ssh;

import java.util.Properties;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {

protected void onCreate(Bundle savedInstanceState) {

JSch jsch = new JSch();
Session session = jsch.getSession("root","", 22);

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


catch (Exception e)

What did I do wrong ? I have no error messages and I don't see any SSH connection on my Linux. I added the libraries jsch and jzlib. I have no problem to get connect with a putty session.

EDIT1 : In fact, I found an error which explain why it doesn't work even if I don't know how to resolve the problem. The error is :


so it seems to mean that the app can't perform a networking operation on its main thread...

Answer Source

You have to execute that code in another thread so you don't hang the UI thread is what that exception means. If the UI thread is executing a network call it can't repaint the UI so your users sees a frozen UI that doesn't respond to them while the app is waiting on the network call to finish. Android wants to avoid bad user experiences like this so it prevents you from doing things like this by throwing this exception.

Your onCreate() method should invoke another thread (I'd suggest using an AsyncTask over a raw thread) to perform the SSH connection. Then when it's done it can post the results back to the UI thread and safely update your application's UI from the UI thread.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download