massh 0.6.3

This library is a simple wrapper around the ssh2 crate to run SSH/SCP commands on a "mass" of hosts in parallel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use anyhow::Result;
use serde::Deserialize;
use ssh2::Session;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::time::Duration;

/// SSH authentication method.
#[derive(Deserialize)]
pub enum SshAuth {
    /// Agent authentication with the first public key found in an SSH agent.
    #[serde(rename = "agent")]
    Agent,
    /// Basic password authentication.
    #[serde(rename = "password")]
    Password(String),
    /// Public key authentication using a PEM encoded private key file stored on disk.
    #[serde(rename = "pubkey")]
    Pubkey(PathBuf),
}

/// SSH command output.
pub struct SshOutput {
    /// Exit status
    pub exit_status: i32,
    /// Standard error
    pub stderr: Vec<u8>,
    /// Standard output
    pub stdout: Vec<u8>,
}

/// SSH client to run commands on a single host.
///
/// ## Public API Overview
///
/// Construct a new `SshClient`:
/// - [`SshClient::from`]
/// - [`SshClient::try_from`]
///
/// Configure this `SshClient`:
/// - [`SshClient::set_auth_agent`]
/// - [`SshClient::set_auth_password`]
/// - [`SshClient::set_auth_pubkey`]
/// - [`SshClient::set_timeout`]
///
/// Inspect this `SshClient`:
/// - [`SshClient::get_addr`]
/// - [`SshClient::get_auth`]
/// - [`SshClient::get_timeout`]
/// - [`SshClient::get_user`]
/// - [`SshClient::is_connected`]
///
/// Run commands with this `SshClient`:
/// - [`SshClient::execute`]
/// - [`SshClient::scp_download`]
/// - [`SshClient::scp_upload`]
///
/// There are also methods to manage the internal authenticated session of this `SshClient`:
/// - [`SshClient::connect`]
/// - [`SshClient::disconnect`]
///
/// However, it's typically not necessary to call them because they are invoked lazily when needed.
///
/// ## Example
///
/// ```no_run
/// use massh::SshClient;
/// use std::net::Ipv4Addr;
///
/// // Construct a new `SshClient` for `username@127.0.0.1:22`.
/// let mut ssh = SshClient::from("username", (Ipv4Addr::LOCALHOST, 22));
///
/// // Configure the client.
/// ssh.set_auth_password("top-secret").set_timeout(5000);
///
/// // Download a file.
/// ssh.scp_download("remote.txt", "local.txt").unwrap();
///
/// // Upload a file.
/// ssh.scp_upload("local.txt", "remote-copy.txt").unwrap();
///
/// // Run a command and print its output.
/// let output = ssh.execute("cat remote-copy.txt").unwrap();
/// println!("status: {}", output.exit_status);
/// println!("stdout: {}", String::from_utf8(output.stdout).unwrap());
/// println!("stderr: {}", String::from_utf8(output.stderr).unwrap());
/// ```
pub struct SshClient {
    addr: SocketAddr,
    auth: SshAuth,
    session: Option<Session>,
    timeout: u64,
    user: String,
}

impl SshClient {
    /// Constructs a new `SshClient` for the specified host's username and address.
    ///
    /// By default, the client uses agent authentication and has no timeout.
    ///
    /// ## Example
    /// ```no_run
    /// use massh::SshClient;
    /// use std::net::Ipv4Addr;
    ///
    /// let ssh = SshClient::from("username", (Ipv4Addr::LOCALHOST, 22));
    /// ```
    pub fn from(user: impl Into<String>, addr: impl Into<SocketAddr>) -> Self {
        Self {
            addr: addr.into(),
            auth: SshAuth::Agent,
            session: None,
            timeout: 0,
            user: user.into(),
        }
    }

    /// Attempts to construct a new `SshClient` for the specified host's username and address.
    ///
    /// Unlike [`SshClient::from`], it can resolve a hostname to an address.
    /// However, it's fallible and therefore returns a `Result`.
    ///
    /// By default, the client uses agent authentication and has no timeout.
    ///
    /// ## Example
    /// ```no_run
    /// use massh::SshClient;
    ///
    /// let ssh1 = SshClient::try_from("username", "127.0.0.1:22").unwrap();
    /// let ssh2 = SshClient::try_from("username", "localhost:22").unwrap();
    /// let ssh3 = SshClient::try_from("ec2-user", "xyz.compute.amazonaws.com:22").unwrap();
    /// ```
    pub fn try_from(user: impl Into<String>, addr: impl ToSocketAddrs) -> Result<Self> {
        if let Some(addr) = addr.to_socket_addrs()?.next() {
            Ok(Self {
                addr,
                auth: SshAuth::Agent,
                session: None,
                timeout: 0,
                user: user.into(),
            })
        } else {
            Err(anyhow::anyhow!("Socket address conversion failed"))
        }
    }

    /// Configures this `SshClient` to perform agent authentication using
    /// the first public key found in an SSH agent.
    ///
    /// This is the default.
    ///
    /// ## Example
    /// ```no_run
    /// let mut ssh = SshClient::from("username", (Ipv4Addr::LOCALHOST, 22));
    ///
    /// // Note that this does nothing since it's the default.
    /// ssh.set_auth_agent();
    /// ```
    pub fn set_auth_agent(&mut self) -> &mut Self {
        self.auth = SshAuth::Agent;
        self
    }

    /// Configures this `SshClient` to perform basic password authentication.
    ///
    /// ## Example
    /// ```no_run
    /// let mut ssh = SshClient::from("username", (Ipv4Addr::LOCALHOST, 22));
    ///
    /// ssh.set_auth_password("top-secret");
    /// ```
    pub fn set_auth_password(&mut self, password: impl Into<String>) -> &mut Self {
        self.auth = SshAuth::Password(password.into());
        self
    }

    /// Configures this `SshClient` to perform public key authentication using
    /// a PEM encoded private key file stored on disk.
    ///
    /// ## Example
    /// ```no_run
    /// let mut ssh = SshClient::from("username", (Ipv4Addr::LOCALHOST, 22));
    ///
    /// ssh.set_auth_pubkey("/home/username/.ssh/id_rsa");
    /// ```
    pub fn set_auth_pubkey(&mut self, path: impl Into<PathBuf>) -> &mut Self {
        self.auth = SshAuth::Pubkey(path.into());
        self
    }

    /// Configures this `SshClient` to use a timeout, in milliseconds, for blocking functions.
    ///
    /// A timeout of zero signifies no timeout. This is the default.
    ///
    /// ## Example
    /// ```no_run
    /// let mut ssh = SshClient::from("username", (Ipv4Addr::LOCALHOST, 22));
    ///
    /// // Set a timeout of 5 seconds.
    /// ssh.set_timeout(5000);
    /// ```
    pub fn set_timeout(&mut self, timeout_ms: u64) -> &mut Self {
        self.timeout = timeout_ms;
        self
    }

    /// Returns the address of this `SshClient`'s configured host.
    pub fn get_addr(&self) -> SocketAddr {
        self.addr
    }

    /// Returns the authentication method of this `SshClient`'s configured host.
    pub fn get_auth(&self) -> &SshAuth {
        &self.auth
    }

    /// Returns the timeout, in milliseconds, of this `SshClient`'s configured host.
    ///
    /// A timeout of zero signifies no timeout.
    pub fn get_timeout(&self) -> u64 {
        self.timeout
    }

    /// Returns the username of this `SshClient`'s configured host.
    pub fn get_user(&self) -> &str {
        &self.user
    }

    /// Returns whether this `SshClient` has established an authenticated session
    /// with the configured host.
    pub fn is_connected(&self) -> bool {
        self.session.is_some()
    }

    /// Attempts to execute a command on the configured host.
    ///
    /// Note that this method implicitly calls [`SshClient::connect`] if no session was
    /// established prior. Otherwise, it reuses the cached session.
    ///
    /// If successful, it returns an [`SshOutput`] containing the exit status, standard output,
    /// and standard error of the command.
    ///
    /// ## Example
    /// ```no_run
    /// let mut ssh = SshClient::from("username", (Ipv4Addr::LOCALHOST, 22));
    ///
    /// let output = ssh.execute("echo $PATH").unwrap();
    ///
    /// println!("status: {}", output.exit_status);
    /// println!("stdout: {}", String::from_utf8(output.stdout).unwrap());
    /// println!("stderr: {}", String::from_utf8(output.stderr).unwrap());
    /// ```
    pub fn execute(&mut self, command: &str) -> Result<SshOutput> {
        // Establish authenticated SSH session.
        if self.session.is_none() {
            self.connect()?;
        }
        let session = self.session.as_ref().unwrap();

        // Open channel and stderr stream.
        let mut channel = session.channel_session()?;
        let mut stderr_stream = channel.stderr();

        // Execute command.
        channel.exec(command)?;

        // Read stdout into buffer.
        let mut stdout = Vec::new();
        channel.read_to_end(&mut stdout)?;

        // Read stderr into buffer.
        let mut stderr = Vec::new();
        stderr_stream.read_to_end(&mut stderr)?;

        // Close channel and retrieve exit status.
        channel.wait_close()?;
        let exit_status = channel.exit_status()?;

        // Return successfully.
        Ok(SshOutput {
            exit_status,
            stdout,
            stderr,
        })
    }

    /// Attempts to download a file from the configured host.
    ///
    /// Note that this method implicitly calls [`SshClient::connect`] if no session was
    /// established prior. Otherwise, it reuses the cached session.
    ///
    /// ## Example
    /// ```no_run
    /// let mut ssh = SshClient::from("username", (Ipv4Addr::LOCALHOST, 22));
    ///
    /// if ssh.scp_download("remote.txt", "local.txt").is_ok() {
    ///     println!("download worked!");
    /// }
    /// ```
    pub fn scp_download<P: AsRef<Path>>(&mut self, remote_path: P, local_path: P) -> Result<()> {
        // Establish authenticated SSH session.
        if self.session.is_none() {
            self.connect()?;
        }
        let session = self.session.as_ref().unwrap();

        // Open channel.
        let (mut channel, _) = session.scp_recv(remote_path.as_ref())?;

        // Read remote file into buffer.
        let mut buffer = Vec::new();
        channel.read_to_end(&mut buffer)?;

        // Write buffer to local file.
        std::fs::write(local_path, &buffer)?;

        // Close channel.
        channel.send_eof()?;
        channel.wait_eof()?;
        channel.close()?;
        channel.wait_close()?;

        // Return successfully.
        Ok(())
    }

    /// Attempts to upload a file to the configured host.
    ///
    /// Note that this method implicitly calls [`SshClient::connect`] if no session was
    /// established prior. Otherwise, it reuses the cached session.
    ///
    /// ## Example
    /// ```no_run
    /// let mut ssh = SshClient::from("username", (Ipv4Addr::LOCALHOST, 22));
    ///
    /// if ssh.scp_upload("local.txt", "remote.txt").is_ok() {
    ///     println!("upload worked!");
    /// }
    /// ```
    pub fn scp_upload<P: AsRef<Path>>(&mut self, local_path: P, remote_path: P) -> Result<()> {
        // Establish authenticated SSH session.
        if self.session.is_none() {
            self.connect()?;
        }
        let session = self.session.as_ref().unwrap();

        // Read local file into buffer.
        let buffer = std::fs::read(local_path)?;
        let size = buffer.len() as u64;

        // Open channel.
        let mut channel = session.scp_send(remote_path.as_ref(), 0o644, size, None)?;

        // Write buffer to remote file.
        channel.write_all(&buffer)?;

        // Close channel.
        channel.send_eof()?;
        channel.wait_eof()?;
        channel.close()?;
        channel.wait_close()?;

        // Return successfully.
        Ok(())
    }

    /// Attempts to establish an authenticated session between this `SshClient`
    /// and the configured host.
    ///
    /// If successful, the session is cached internally by the client and is reused when
    /// running multiple commands with [`SshClient::execute`], [`SshClient::scp_download`],
    /// or [`SshClient::scp_upload`].
    ///
    /// Note that it's not strictly necessary to call this method because the 3 methods
    /// mentioned above will invoke it lazily if no session was established prior.
    ///
    /// Finally, if the first session succeeds but the second session fails,
    /// the first session will remain cached internally by the client. If the second
    /// session succeeds, it replaces the first session (which is dropped).
    ///
    /// ## Example
    /// ```no_run
    /// let mut ssh = SshClient::from("username", (Ipv4Addr::LOCALHOST, 22));
    ///
    /// if ssh.connect().is_ok() {
    ///     println!("agent authentication worked!");
    /// }
    ///
    /// if ssh.set_auth_password("top-secret").connect().is_ok() {
    ///     println!("password authentication also worked!");
    /// }
    /// ```
    pub fn connect(&mut self) -> Result<&mut Self> {
        // Initialize new SSH session.
        let mut session = Session::new()?;

        // Open a TCP connection to the configured host and attach it to the SSH session.
        let tcp_stream = if self.timeout == 0 {
            // If timeout is zero, don't set a timeout.
            TcpStream::connect(&self.addr)?
        } else {
            // If timeout is non-zero, set a timeout on both the SSH session and the TCP stream.
            session.set_timeout(self.timeout as u32);
            TcpStream::connect_timeout(&self.addr, Duration::from_millis(self.timeout))?
        };
        session.set_tcp_stream(tcp_stream);

        // Perform SSH handshake.
        session.handshake()?;

        // Perform SSH authentication based on selected method.
        match &self.auth {
            SshAuth::Agent => session.userauth_agent(&self.user)?,
            SshAuth::Password(password) => session.userauth_password(&self.user, password)?,
            SshAuth::Pubkey(path) => session.userauth_pubkey_file(&self.user, None, path, None)?,
        }

        // Confirm that the session is authenticated.
        if !session.authenticated() {
            return Err(anyhow::anyhow!("Authentication failed"));
        }

        // Cache authenticated session and return successfully.
        self.session = Some(session);
        Ok(self)
    }

    /// Drops the authenticated session between this `SshClient` and the configured host,
    /// or does nothing if no session was established prior.
    ///
    /// Note that it's not strictly necessary to call this method because it is invoked
    /// implicitly when the client itself is dropped.
    ///
    /// ## Example
    /// ```no_run
    /// let mut ssh = SshClient::from("username", (Ipv4Addr::LOCALHOST, 22));
    ///
    /// ssh.connect().unwrap();
    /// // Do some stuff...
    /// ssh.disconnect();
    /// ```
    pub fn disconnect(&mut self) -> &mut Self {
        self.session = None;
        self
    }
}