Sample code for 30+ languages & platforms
Android™

Run a Single SSH Command and Get the Output

See more SSH Examples

Demonstrates the Chilkat Ssh.QuickCommand method, which runs one noninteractive remote command and returns its stdout as text. The first argument is the command and the second is the charset used to decode the output. Internally it opens a session channel, sends an exec request, and receives the output through EOF.

Background: This collapses the whole open-channel / exec / receive / retrieve sequence into a single call, and it is the right choice for the common case of "run one command and give me the output." Because no PTY is involved the output is clean and parseable, with no prompt or echoed input. Reach for the individual channel methods only when you need stderr separately, the exit status, or an interactive session.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    //  Demonstrates the Ssh.QuickCommand method, which runs one noninteractive remote command and
    //  returns its stdout as text.  The 1st argument is the command and the 2nd is the charset used
    //  to decode the output.  Internally it opens a session channel, sends an exec request, and
    //  receives the output through EOF.

    CkSsh ssh = new CkSsh();

    int sshPort = 22;
    success = ssh.Connect("ssh.example.com",sshPort);
    if (success == false) {
        Log.i(TAG, ssh.lastErrorText());
        return;
        }

    //  Normally you would not hard-code the password in source.  You should instead obtain it
    //  from an interactive prompt, environment variable, or a secrets vault.
    String password = "mySshPassword";

    success = ssh.AuthenticatePw("mySshLogin",password);
    if (success == false) {
        Log.i(TAG, ssh.lastErrorText());
        return;
        }

    //  Run a single command and collect its output in one call.
    String output = ssh.quickCommand("uname -a","utf-8");
    if (ssh.get_LastMethodSuccess() == false) {
        Log.i(TAG, ssh.lastErrorText());
        return;
        }

    Log.i(TAG, output);

    ssh.Disconnect();

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}