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
impl SshClient
Sourcepub fn new(ssh_config: SshConfig) -> Self
pub fn new(ssh_config: SshConfig) -> Self
Creates a new SshClient
§Arguments
ssh_config- SSH connection configuration containing credentials and host IP
Sourcepub fn ssh_config(&self) -> &SshConfig
pub fn ssh_config(&self) -> &SshConfig
Get the SSH configuration
Returns a reference to the SSH configuration used by this client.
Sourcepub fn execute(&self, remote_command: &str) -> Result<String, CommandError>
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 succeedsErr(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
Sourcepub fn check_command(&self, remote_command: &str) -> Result<bool, CommandError>
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 otherwiseErr(CommandError)- Error if SSH connection could not be established
§Errors
This function will return an error if:
- The SSH connection cannot be established
Sourcepub fn test_connectivity(&self) -> Result<bool, CommandError>
pub fn test_connectivity(&self) -> Result<bool, CommandError>
Sourcepub async fn wait_for_connectivity(&self) -> Result<(), SshError>
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 establishedErr(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
Sourcepub fn execute_with_options(
&self,
remote_command: &str,
additional_options: &[&str],
) -> Result<String, CommandError>
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 hostadditional_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.
Sourcepub fn check_command_with_options(
&self,
remote_command: &str,
additional_options: &[&str],
) -> Result<bool, CommandError>
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 hostadditional_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§
impl Freeze for SshClient
impl RefUnwindSafe for SshClient
impl Send for SshClient
impl Sync for SshClient
impl Unpin for SshClient
impl UnsafeUnpin for SshClient
impl UnwindSafe for SshClient
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
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 moreSource§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
Source§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request