Java – Use the Android App to execute SSH commands on the Raspberry Pi

Use the Android App to execute SSH commands on the Raspberry Pi… here is a solution to the problem.

Use the Android App to execute SSH commands on the Raspberry Pi

I’m trying to send commands to my Raspberry Pi using an Android app with SSH. This command can only be executed by the Raspberry Pi, and I don’t need to save any OutputStreams. It was working when I sent the command “sudo reboot” because the Pi was performing a reboot when I pressed the button on the app. What I really want to do is start the program first with the command “cd Desktop” and then “sudo java -classpath .:classes:/opt/pi4j/lib/’*’ SimpleTextServer”.

I figured out how to use This with the following code, The application itself is running, it just sends commands to Pi and Pi executes those commands.

Here’s the code (not everything, I hope).

public class SlimpleTextClientActivity extends Activity implements OnClickListener{

private Button buttonSSH;

    protected void onCreate(Bundle savedInstanceState) {

Button press event listener
    buttonSSH.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            new AsyncTask<Integer, Void, Void>() {
                protected Void doInBackground(Integer... params) {
                    try {
                        Ausgabe = executeRemoteCommand("pi", "raspberry", "", 22);
                    } catch (Exception e) {
                    return null;

public static String executeRemoteCommand(String username,String password,String hostname,int port)
        throws Exception {
    JSch jsch = new JSch();
    Session session = jsch.getSession(username, hostname, port);

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


 SSH Channel
    ChannelExec channelssh = (ChannelExec)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

 Execute command
    channelssh.setCommand("cd Desktop");
    channelssh.setCommand("sudo java -classpath .:classes:/opt/pi4j/lib/'*' SimpleTextServer");
    channelssh.setCommand("sudo reboot");

return baos.toString();

Thank you very much for your help, please let me know if I should post any further code or information.


EDIT: So I’m sure the code itself works fine, for example, if I send the command “lsusb > home/pi/text.txt”, it creates a text file with terminal output in this directory. So how do I change the code where it only runs commands (and possibly shows it on the terminal of the Raspberry Pi)?


According to Multiple commands using JSch
You can try:

channelssh.setCommand("cd Desktop; sudo java -classpath .:classes:/opt/pi4j/lib/'*' SimpleTextServer");

Related Problems and Solutions