BlogBeast
ESP32

Building an SSH Client on ESP32

By BlogBeast · · 4 min read

An ESP32 can do more than blink LEDs. With an SSH client on board it can log in to a Linux box, run a command and read the result. That opens up neat projects: a button that restarts a service, a display that shows a server’s uptime, or a sensor node that reports to a home server without exposing a plain-text protocol.

In this guide we will build a small SSH client with the Arduino framework. It connects to Wi-Fi, opens an SSH session, checks the server’s host key, logs in and runs one command.

What you need

Version note: the library’s README says it is built and tested against versions 2.0.17 and 3.0.7 of the ESP32 Arduino core. If you hit odd build errors, check your core version first.

How the library works

LibSSH-ESP32 is a port of the well-known libssh library, so you use the regular libssh API. You include libssh_esp32.h, call libssh_begin() once at startup, and then use functions such as ssh_new, ssh_connect and ssh_channel_request_exec. If you have read libssh examples for Linux, the flow will look familiar.

The complete sketch

Fill in your Wi-Fi details, the target host and a user. The sketch runs uname -a && uptime on the remote machine and prints the answer to the Serial Monitor.

#include <WiFi.h>
#include "libssh_esp32.h"
#include <libssh/libssh.h>

const char* WIFI_SSID = "your-wifi-name";
const char* WIFI_PASS = "your-wifi-password";

const char* SSH_HOST  = "192.168.1.50";   // the machine you want to log in to
const int   SSH_PORT  = 22;
const char* SSH_USER  = "pi";
const char* SSH_PASS  = "change-me";      // prefer key auth for anything real

// Paste the output of: ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub
const char* EXPECTED_FINGERPRINT = "SHA256:PASTE_YOUR_HOST_KEY_FINGERPRINT_HERE";

bool hostKeyMatches(ssh_session session) {
  ssh_key key;
  if (ssh_get_server_publickey(session, &key) != SSH_OK) return false;
  unsigned char* hash = NULL;
  size_t len = 0;
  int rc = ssh_get_publickey_hash(key, SSH_PUBLICKEY_HASH_SHA256, &hash, &len);
  ssh_key_free(key);
  if (rc != 0) return false;
  char* fp = ssh_get_fingerprint_hash(SSH_PUBLICKEY_HASH_SHA256, hash, len);
  ssh_clean_pubkey_hash(&hash);
  bool ok = fp && strcmp(fp, EXPECTED_FINGERPRINT) == 0;
  if (fp) ssh_string_free_char(fp);
  return ok;
}

void runRemoteCommand(const char* cmd) {
  ssh_session session = ssh_new();
  if (!session) { Serial.println("ssh_new failed"); return; }

  int port = SSH_PORT;
  ssh_options_set(session, SSH_OPTIONS_HOST, SSH_HOST);
  ssh_options_set(session, SSH_OPTIONS_PORT, &port);
  ssh_options_set(session, SSH_OPTIONS_USER, SSH_USER);

  if (ssh_connect(session) != SSH_OK) {
    Serial.printf("Connect failed: %s\n", ssh_get_error(session));
    ssh_free(session);
    return;
  }
  if (!hostKeyMatches(session)) {
    Serial.println("Host key does not match. Refusing to continue.");
    ssh_disconnect(session); ssh_free(session);
    return;
  }
  if (ssh_userauth_password(session, NULL, SSH_PASS) != SSH_AUTH_SUCCESS) {
    Serial.printf("Login failed: %s\n", ssh_get_error(session));
    ssh_disconnect(session); ssh_free(session);
    return;
  }

  ssh_channel channel = ssh_channel_new(session);
  if (channel && ssh_channel_open_session(channel) == SSH_OK &&
      ssh_channel_request_exec(channel, cmd) == SSH_OK) {
    char buf[256];
    int n;
    while ((n = ssh_channel_read(channel, buf, sizeof(buf), 0)) > 0) {
      Serial.write((uint8_t*)buf, n);
    }
    ssh_channel_send_eof(channel);
  } else {
    Serial.println("Could not run the command");
  }
  if (channel) { ssh_channel_close(channel); ssh_channel_free(channel); }
  ssh_disconnect(session);
  ssh_free(session);
}

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); }
  Serial.printf("\nWiFi connected, IP: %s\n", WiFi.localIP().toString().c_str());

  libssh_begin();                          // initialise libssh once
  runRemoteCommand("uname -a && uptime");
}

void loop() {}

Step by step

  1. Connect to Wi-Fi. The usual WiFi.begin() loop. SSH needs a working network first.
  2. Initialise libssh. libssh_begin() sets up the port once.
  3. Create a session and set options. Host, port and user are options on the session object.
  4. Connect, then verify the host key. This step is what protects you from connecting to an impostor.
  5. Authenticate. The example uses a password. Public key authentication is better.
  6. Open a channel and run the command. Read the output in a loop until it returns zero.
  7. Clean up. Close and free the channel and session so you do not leak memory on a small device.

Get your host key fingerprint

On the server, run this and paste the SHA256:... value into the sketch:

ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub

Without this check, anyone who can intercept your network traffic could pretend to be your server. A microcontroller has no known_hosts file, so pinning the fingerprint in your code is a simple and effective substitute.

Security checklist

Troubleshooting

Ideas to build next

Trigger a backup when you press a button. Show uptime and disk usage on an OLED. Use the ESP32 as a tiny remote for your home server. The pattern is always the same: connect, verify, authenticate, run, read and close.

Note: please test this sketch on your own hardware and library version. Boards, cores and libraries change, and you should adapt the code to your setup.