Skip to main content

SshClient

Struct SshClient 

Source
pub struct SshClient { /* private fields */ }
Expand description

A specialized SSH client with predefined security settings

This client provides a secure SSH interface for connecting to remote hosts with:

  • Private key authentication
  • Disabled strict host key checking (for automation)
  • No known hosts file usage
  • Consistent connection settings

Uses CommandExecutor as a collaborator for actual command execution.

Implementations§

Source§

impl SshClient

Source

pub fn new(ssh_config: SshConfig) -> Self

Creates a new SshClient

§Arguments
  • ssh_config - SSH connection configuration containing credentials and host IP
Source

pub fn ssh_config(&self) -> &SshConfig

Get the SSH configuration

Returns a reference to the SSH configuration used by this client.

Source

pub fn execute(&self, remote_command: &str) -> Result<String, CommandError>

Execute a command on a remote host via SSH

§Arguments
  • remote_command - Command to execute on the remote host
§Returns
  • Ok(String) - The stdout output if the command succeeds
  • Err(CommandError) - Error describing what went wrong
§Errors

This function will return an error if:

  • The SSH connection cannot be established
  • The remote command execution fails with a non-zero exit code
Source

pub fn check_command(&self, remote_command: &str) -> Result<bool, CommandError>

Check if a command succeeds on a remote host (returns only status)

§Arguments
  • remote_command - Command to execute on the remote host
§Returns
  • Ok(bool) - true if command succeeded (exit code 0), false otherwise
  • Err(CommandError) - Error if SSH connection could not be established
§Errors

This function will return an error if:

  • The SSH connection cannot be established
Source

pub fn test_connectivity(&self) -> Result<bool, CommandError>

Test SSH connectivity to a host

Uses the connection timeout configured in SshConfig.

§Returns
  • Ok(bool) - true if SSH connection succeeds, false otherwise
  • Err(CommandError) - Error if SSH command could not be started
§Errors

This function will return an error if:

  • The SSH command could not be started
Source

pub async fn wait_for_connectivity(&self) -> Result<(), SshError>

Wait for SSH connectivity to be established with retry logic

This method will repeatedly attempt to connect via SSH until successful or the maximum number of attempts is reached. Progress is reported via structured logging using the tracing crate.

§Returns
  • Ok(()) - SSH connectivity was successfully established
  • Err(SshError) - SSH connectivity could not be established after all attempts
§Errors

This function will return an error if:

  • SSH connectivity cannot be established after the configured maximum attempts
Source

pub fn execute_with_options( &self, remote_command: &str, additional_options: &[&str], ) -> Result<String, CommandError>

Execute a command with additional SSH options

This method allows passing custom SSH options for specific commands, useful for advanced scenarios like connection keep-alive or custom timeouts.

§Arguments
  • remote_command - Command to execute on the remote host
  • additional_options - SSH options (e.g., ["ServerAliveInterval=60"])
§Examples
use torrust_tracker_deployer_lib::adapters::ssh::{SshClient, SshConfig, SshCredentials};
use torrust_tracker_deployer_lib::shared::Username;
use std::path::PathBuf;
use std::net::{IpAddr, Ipv4Addr};

let credentials = SshCredentials::new(
    PathBuf::from("/path/to/key"),
    PathBuf::from("/path/to/key.pub"),
    Username::new("user")?,
);
let config = SshConfig::with_default_port(
    credentials,
    IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100))
);
let client = SshClient::new(config);

// Keep connection alive during long-running command
let output = client.execute_with_options(
    "long_running_task",
    &["ServerAliveInterval=60", "ServerAliveCountMax=3"]
)?;

// Use custom connection timeout for specific command
let output = client.execute_with_options(
    "quick_check",
    &["ConnectTimeout=2"]
)?;
§Errors

Returns CommandError::ExecutionFailed if the command exits with non-zero status, or CommandError::IoError if SSH execution fails.

Source

pub fn check_command_with_options( &self, remote_command: &str, additional_options: &[&str], ) -> Result<bool, CommandError>

Check if a command succeeds with additional SSH options

Wrapper around execute_with_options that returns true if the command exits with code 0, false otherwise. Ideal for service checks and validation.

§Arguments
  • remote_command - Command to execute on the remote host
  • additional_options - SSH options (e.g., ["ConnectTimeout=2"])
§Examples
use torrust_tracker_deployer_lib::adapters::ssh::{SshClient, SshConfig, SshCredentials};
use torrust_tracker_deployer_lib::shared::Username;
use std::path::PathBuf;
use std::net::{IpAddr, Ipv4Addr};

let credentials = SshCredentials::new(
    PathBuf::from("/path/to/key"),
    PathBuf::from("/path/to/key.pub"),
    Username::new("user")?,
);
let config = SshConfig::with_default_port(
    credentials,
    IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100))
);
let client = SshClient::new(config);

// Quick service check with short timeout
let is_running = client.check_command_with_options(
    "systemctl is-active myservice",
    &["ConnectTimeout=2"]
)?;

if is_running {
    println!("Service is running");
}
§Errors

Returns CommandError::IoError if SSH connection fails. Command failures (non-zero exit) return Ok(false), not an error.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<T> IntoResult<T> for T

Source§

type Err = !

Source§

fn into_result(self) -> Result<T, <T as IntoResult<T>>::Err>

Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more