#ssh-client #remote-command-execution #execution-client #command #client #ssh

lmrc-ssh

SSH client library for the LMRC Stack - comprehensive library for executing remote SSH commands programmatically

29 releases

Uses new Rust 2024

0.3.16 Dec 11, 2025
0.3.15 Dec 11, 2025
0.3.9 Nov 30, 2025
0.2.12 Nov 27, 2025
0.1.0 Nov 26, 2025

#1696 in Network programming


Used in 6 crates (5 directly)

MIT/Apache

29KB
318 lines

lmrc-ssh

Part of the LMRC Stack - Infrastructure-as-Code toolkit for building production-ready Rust applications

Crates.io Documentation License

A comprehensive Rust library for executing SSH commands programmatically. Built on top of the robust ssh2 library, lmrc-ssh provides a clean, intuitive API for managing SSH connections and executing remote commands.

Features

  • 🔐 Flexible Authentication - Support for password and public key authentication
  • 🚀 Simple API - Intuitive builder pattern for easy connection setup
  • 📦 Batch Execution - Execute multiple commands in sequence
  • 🛡️ Comprehensive Error Handling - Detailed error types with helpful messages
  • 📚 Well Documented - Extensive documentation with examples
  • Well Tested - Thorough test coverage

Installation

Add this to your Cargo.toml:

[dependencies]
lmrc-ssh = "0.1"

Quick Start

Password Authentication

use lmrc_ssh::{SshClient, AuthMethod};

fn main() -> Result<(), lmrc_ssh::Error> {
    let mut client = SshClient::new("example.com", 22)?
        .with_auth(AuthMethod::Password {
            username: "user".to_string(),
            password: "password".to_string(),
        })
        .connect()?;

    let output = client.execute("hostname")?;
    println!("Hostname: {}", output.stdout);

    Ok(())
}

Public Key Authentication

use lmrc_ssh::{SshClient, AuthMethod};

fn main() -> Result<(), lmrc_ssh::Error> {
    let mut client = SshClient::new("example.com", 22)?
        .with_auth(AuthMethod::PublicKey {
            username: "user".to_string(),
            private_key_path: "/home/user/.ssh/id_rsa".to_string(),
            passphrase: None,
        })
        .connect()?;

    let output = client.execute("ls -la")?;
    println!("Output:\n{}", output.stdout);

    Ok(())
}

Usage Examples

Executing Multiple Commands

use lmrc_ssh::{SshClient, AuthMethod};

fn main() -> Result<(), lmrc_ssh::Error> {
    let mut client = SshClient::new("192.168.1.100", 22)?
        .with_auth(AuthMethod::Password {
            username: "admin".to_string(),
            password: "secret".to_string(),
        })
        .connect()?;

    let commands = vec!["whoami", "hostname", "pwd"];
    let outputs = client.execute_batch(&commands)?;

    for (cmd, output) in commands.iter().zip(outputs.iter()) {
        println!("Command: {}", cmd);
        println!("Output: {}", output.stdout);
        println!("---");
    }

    Ok(())
}

Handling Command Output

use lmrc_ssh::{SshClient, AuthMethod};

fn main() -> Result<(), lmrc_ssh::Error> {
    let mut client = SshClient::new("example.com", 22)?
        .with_auth(AuthMethod::Password {
            username: "user".to_string(),
            password: "pass".to_string(),
        })
        .connect()?;

    let output = client.execute("some-command")?;

    if output.is_success() {
        println!("Success! Output: {}", output.stdout);
    } else {
        eprintln!("Command failed with exit code: {}", output.exit_status);
        eprintln!("Error: {}", output.stderr);
    }

    Ok(())
}

Error Handling

use lmrc_ssh::{SshClient, AuthMethod, Error};

fn main() {
    let result = SshClient::new("example.com", 22)
        .and_then(|client| {
            client.with_auth(AuthMethod::Password {
                username: "user".to_string(),
                password: "wrong_password".to_string(),
            })
            .connect()
        });

    match result {
        Ok(_) => println!("Connected successfully"),
        Err(Error::AuthenticationFailed { username, reason }) => {
            eprintln!("Authentication failed for {}: {}", username, reason);
        }
        Err(Error::ConnectionFailed { host, port, .. }) => {
            eprintln!("Failed to connect to {}:{}", host, port);
        }
        Err(e) => eprintln!("Error: {}", e),
    }
}

API Overview

SshClient

The main client for SSH connections.

  • new(host, port) - Create a new client instance
  • with_auth(auth_method) - Set the authentication method
  • connect() - Establish the SSH connection
  • execute(command) - Execute a single command
  • execute_batch(commands) - Execute multiple commands
  • is_connected() - Check if the client is connected

AuthMethod

Authentication methods for SSH:

  • Password { username, password } - Password authentication
  • PublicKey { username, private_key_path, passphrase } - Public key authentication

CommandOutput

Represents the output of an executed command:

  • stdout - Standard output
  • stderr - Standard error
  • exit_status - Exit status code
  • is_success() - Check if the command succeeded
  • is_failure() - Check if the command failed
  • combined_output() - Get stdout + stderr combined

Error Types

Comprehensive error types for better error handling:

  • ConnectionFailed - Failed to establish TCP connection
  • AuthenticationFailed - Authentication failed
  • ExecutionFailed - Command execution failed
  • NotConnected - Client is not connected
  • InvalidConfig - Invalid configuration
  • And more...

Examples

Check out the examples directory for more usage examples:

  • simple_connection.rs - Basic SSH connection and command execution
  • batch_commands.rs - Execute multiple commands
  • error_handling.rs - Comprehensive error handling examples

Run an example with:

cargo run --example simple_connection

Testing

Run the test suite:

cargo test

Run tests with output:

cargo test -- --nocapture

Building Documentation

Generate and view the documentation:

cargo doc --open

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

Part of the LMRC Stack project. Licensed under either of:

at your option.

Acknowledgments

This library is built on top of the excellent ssh2 crate.

Security

If you discover a security vulnerability, please email lemarc.dev@gmail.com.

Changelog

See CHANGELOG.md for release history.

Dependencies

~5MB
~105K SLoC