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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
use russh::client::KeyboardInteractiveAuthResponse;
use russh::{
Channel,
client::{Config, Handle, Handler, Msg},
};
use russh_sftp::{client::SftpSession, protocol::OpenFlags};
use std::net::SocketAddr;
use std::sync::Arc;
use std::{fmt::Debug, path::Path};
use std::{io, path::PathBuf};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use super::ToSocketAddrsWithHostname;
/// An authentification token.
///
/// Used when creating a [`Client`] for authentification.
/// Supports password, private key, public key, SSH agent, and keyboard interactive authentication.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AuthMethod {
Password(String),
PrivateKey {
/// entire contents of private key file
key_data: String,
key_pass: Option<String>,
},
PrivateKeyFile {
key_file_path: PathBuf,
key_pass: Option<String>,
},
#[cfg(not(target_os = "windows"))]
PublicKeyFile {
key_file_path: PathBuf,
},
#[cfg(not(target_os = "windows"))]
Agent,
KeyboardInteractive(AuthKeyboardInteractive),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct PromptResponse {
exact: bool,
prompt: String,
response: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub struct AuthKeyboardInteractive {
/// Hnts to the server the preferred methods to be used for authentication.
submethods: Option<String>,
responses: Vec<PromptResponse>,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ServerCheckMethod {
NoCheck,
/// base64 encoded key without the type prefix or hostname suffix (type is already encoded)
PublicKey(String),
PublicKeyFile(String),
DefaultKnownHostsFile,
KnownHostsFile(String),
}
impl AuthMethod {
/// Convenience method to create a [`AuthMethod`] from a string literal.
pub fn with_password(password: &str) -> Self {
Self::Password(password.to_string())
}
pub fn with_key(key: &str, passphrase: Option<&str>) -> Self {
Self::PrivateKey {
key_data: key.to_string(),
key_pass: passphrase.map(str::to_string),
}
}
pub fn with_key_file<T: AsRef<Path>>(key_file_path: T, passphrase: Option<&str>) -> Self {
Self::PrivateKeyFile {
key_file_path: key_file_path.as_ref().to_path_buf(),
key_pass: passphrase.map(str::to_string),
}
}
#[cfg(not(target_os = "windows"))]
pub fn with_public_key_file<T: AsRef<Path>>(key_file_path: T) -> Self {
Self::PublicKeyFile {
key_file_path: key_file_path.as_ref().to_path_buf(),
}
}
/// Creates a new SSH agent authentication method.
///
/// This will attempt to authenticate using all identities available in the SSH agent.
/// The SSH agent must be running and the SSH_AUTH_SOCK environment variable must be set.
///
/// # Example
/// ```no_run
/// use bssh::ssh::tokio_client::AuthMethod;
///
/// let auth = AuthMethod::with_agent();
/// ```
///
/// # Platform Support
/// This method is only available on Unix-like systems (Linux, macOS, etc.).
/// It is not available on Windows.
#[cfg(not(target_os = "windows"))]
pub fn with_agent() -> Self {
Self::Agent
}
pub const fn with_keyboard_interactive(auth: AuthKeyboardInteractive) -> Self {
Self::KeyboardInteractive(auth)
}
}
impl AuthKeyboardInteractive {
pub fn new() -> Self {
Default::default()
}
/// Hnts to the server the preferred methods to be used for authentication.
pub fn with_submethods(mut self, submethods: impl Into<String>) -> Self {
self.submethods = Some(submethods.into());
self
}
/// Adds a response to the list of responses for a given prompt.
///
/// The comparison for the prompt is done using a "contains".
pub fn with_response(mut self, prompt: impl Into<String>, response: impl Into<String>) -> Self {
self.responses.push(PromptResponse {
exact: false,
prompt: prompt.into(),
response: response.into(),
});
self
}
/// Adds a response to the list of responses for a given exact prompt.
pub fn with_response_exact(
mut self,
prompt: impl Into<String>,
response: impl Into<String>,
) -> Self {
self.responses.push(PromptResponse {
exact: true,
prompt: prompt.into(),
response: response.into(),
});
self
}
}
impl PromptResponse {
fn matches(&self, received_prompt: &str) -> bool {
if self.exact {
self.prompt.eq(received_prompt)
} else {
received_prompt.contains(&self.prompt)
}
}
}
impl From<AuthKeyboardInteractive> for AuthMethod {
fn from(value: AuthKeyboardInteractive) -> Self {
Self::with_keyboard_interactive(value)
}
}
impl ServerCheckMethod {
/// Convenience method to create a [`ServerCheckMethod`] from a string literal.
pub fn with_public_key(key: &str) -> Self {
Self::PublicKey(key.to_string())
}
/// Convenience method to create a [`ServerCheckMethod`] from a string literal.
pub fn with_public_key_file(key_file_name: &str) -> Self {
Self::PublicKeyFile(key_file_name.to_string())
}
/// Convenience method to create a [`ServerCheckMethod`] from a string literal.
pub fn with_known_hosts_file(known_hosts_file: &str) -> Self {
Self::KnownHostsFile(known_hosts_file.to_string())
}
}
/// A ssh connection to a remote server.
///
/// After creating a `Client` by [`connect`]ing to a remote host,
/// use [`execute`] to send commands and receive results through the connections.
///
/// [`connect`]: Client::connect
/// [`execute`]: Client::execute
///
/// # Examples
///
/// ```no_run
/// use bssh::ssh::tokio_client::{Client, AuthMethod, ServerCheckMethod};
/// #[tokio::main]
/// async fn main() -> Result<(), bssh::ssh::tokio_client::Error> {
/// let mut client = Client::connect(
/// ("10.10.10.2", 22),
/// "root",
/// AuthMethod::with_password("root"),
/// ServerCheckMethod::NoCheck,
/// ).await?;
///
/// let result = client.execute("echo Hello SSH").await?;
/// assert_eq!(result.stdout, "Hello SSH\n");
/// assert_eq!(result.exit_status, 0);
///
/// Ok(())
/// }
#[derive(Clone)]
pub struct Client {
connection_handle: Arc<Handle<ClientHandler>>,
username: String,
address: SocketAddr,
}
impl Client {
/// Open a ssh connection to a remote host.
///
/// `addr` is an address of the remote host. Anything which implements
/// [`ToSocketAddrsWithHostname`] trait can be supplied for the address;
/// ToSocketAddrsWithHostname reimplements all of [`ToSocketAddrs`];
/// see this trait's documentation for concrete examples.
///
/// If `addr` yields multiple addresses, `connect` will be attempted with
/// each of the addresses until a connection is successful.
/// Authentification is tried on the first successful connection and the whole
/// process aborted if this fails.
pub async fn connect(
addr: impl ToSocketAddrsWithHostname,
username: &str,
auth: AuthMethod,
server_check: ServerCheckMethod,
) -> Result<Self, super::Error> {
Self::connect_with_config(addr, username, auth, server_check, Config::default()).await
}
/// Same as `connect`, but with the option to specify a non default
/// [`russh::client::Config`].
pub async fn connect_with_config(
addr: impl ToSocketAddrsWithHostname,
username: &str,
auth: AuthMethod,
server_check: ServerCheckMethod,
config: Config,
) -> Result<Self, super::Error> {
let config = Arc::new(config);
// Connection code inspired from std::net::TcpStream::connect and std::net::each_addr
let socket_addrs = addr
.to_socket_addrs()
.map_err(super::Error::AddressInvalid)?;
let mut connect_res = Err(super::Error::AddressInvalid(io::Error::new(
io::ErrorKind::InvalidInput,
"could not resolve to any addresses",
)));
for socket_addr in socket_addrs {
let handler = ClientHandler {
hostname: addr.hostname(),
host: socket_addr,
server_check: server_check.clone(),
};
match russh::client::connect(config.clone(), socket_addr, handler).await {
Ok(h) => {
connect_res = Ok((socket_addr, h));
break;
}
Err(e) => connect_res = Err(e),
}
}
let (address, mut handle) = connect_res?;
let username = username.to_string();
Self::authenticate(&mut handle, &username, auth).await?;
Ok(Self {
connection_handle: Arc::new(handle),
username,
address,
})
}
/// This takes a handle and performs authentification with the given method.
async fn authenticate(
handle: &mut Handle<ClientHandler>,
username: &String,
auth: AuthMethod,
) -> Result<(), super::Error> {
match auth {
AuthMethod::Password(password) => {
let is_authentificated = handle.authenticate_password(username, password).await?;
if !is_authentificated.success() {
return Err(super::Error::PasswordWrong);
}
}
AuthMethod::PrivateKey { key_data, key_pass } => {
let cprivk = russh::keys::decode_secret_key(key_data.as_str(), key_pass.as_deref())
.map_err(super::Error::KeyInvalid)?;
let is_authentificated = handle
.authenticate_publickey(
username,
russh::keys::PrivateKeyWithHashAlg::new(
Arc::new(cprivk),
handle.best_supported_rsa_hash().await?.flatten(),
),
)
.await?;
if !is_authentificated.success() {
return Err(super::Error::KeyAuthFailed);
}
}
AuthMethod::PrivateKeyFile {
key_file_path,
key_pass,
} => {
let cprivk = russh::keys::load_secret_key(key_file_path, key_pass.as_deref())
.map_err(super::Error::KeyInvalid)?;
let is_authentificated = handle
.authenticate_publickey(
username,
russh::keys::PrivateKeyWithHashAlg::new(
Arc::new(cprivk),
handle.best_supported_rsa_hash().await?.flatten(),
),
)
.await?;
if !is_authentificated.success() {
return Err(super::Error::KeyAuthFailed);
}
}
#[cfg(not(target_os = "windows"))]
AuthMethod::PublicKeyFile { key_file_path } => {
let cpubk = russh::keys::load_public_key(key_file_path)
.map_err(super::Error::KeyInvalid)?;
let mut agent = russh::keys::agent::client::AgentClient::connect_env()
.await
.unwrap();
let mut auth_identity: Option<russh::keys::PublicKey> = None;
for identity in agent
.request_identities()
.await
.map_err(super::Error::KeyInvalid)?
{
if identity == cpubk {
auth_identity = Some(identity.clone());
break;
}
}
if auth_identity.is_none() {
return Err(super::Error::KeyAuthFailed);
}
let is_authentificated = handle
.authenticate_publickey_with(
username,
cpubk,
handle.best_supported_rsa_hash().await?.flatten(),
&mut agent,
)
.await?;
if !is_authentificated.success() {
return Err(super::Error::KeyAuthFailed);
}
}
#[cfg(not(target_os = "windows"))]
AuthMethod::Agent => {
let mut agent = russh::keys::agent::client::AgentClient::connect_env()
.await
.map_err(|_| super::Error::AgentConnectionFailed)?;
let identities = agent
.request_identities()
.await
.map_err(|_| super::Error::AgentRequestIdentitiesFailed)?;
if identities.is_empty() {
return Err(super::Error::AgentNoIdentities);
}
let mut auth_success = false;
for identity in identities {
let result = handle
.authenticate_publickey_with(
username,
identity.clone(),
handle.best_supported_rsa_hash().await?.flatten(),
&mut agent,
)
.await;
if let Ok(auth_result) = result
&& auth_result.success()
{
auth_success = true;
break;
}
}
if !auth_success {
return Err(super::Error::AgentAuthenticationFailed);
}
}
AuthMethod::KeyboardInteractive(mut kbd) => {
let mut res = handle
.authenticate_keyboard_interactive_start(username, kbd.submethods)
.await?;
loop {
let prompts = match res {
KeyboardInteractiveAuthResponse::Success => break,
KeyboardInteractiveAuthResponse::Failure { .. } => {
return Err(super::Error::KeyboardInteractiveAuthFailed);
}
KeyboardInteractiveAuthResponse::InfoRequest { prompts, .. } => prompts,
};
let mut responses = vec![];
for prompt in prompts {
let Some(pos) = kbd
.responses
.iter()
.position(|pr| pr.matches(&prompt.prompt))
else {
return Err(super::Error::KeyboardInteractiveNoResponseForPrompt(
prompt.prompt,
));
};
let pr = kbd.responses.remove(pos);
responses.push(pr.response);
}
res = handle
.authenticate_keyboard_interactive_respond(responses)
.await?;
}
}
};
Ok(())
}
pub async fn get_channel(&self) -> Result<Channel<Msg>, super::Error> {
self.connection_handle
.channel_open_session()
.await
.map_err(super::Error::SshError)
}
/// Open a TCP/IP forwarding channel.
///
/// This opens a `direct-tcpip` channel to the given target.
pub async fn open_direct_tcpip_channel<
T: ToSocketAddrsWithHostname,
S: Into<Option<SocketAddr>>,
>(
&self,
target: T,
src: S,
) -> Result<Channel<Msg>, super::Error> {
let targets = target
.to_socket_addrs()
.map_err(super::Error::AddressInvalid)?;
let src = src
.into()
.map(|src| (src.ip().to_string(), src.port().into()))
.unwrap_or_else(|| ("127.0.0.1".to_string(), 22));
let mut connect_err = super::Error::AddressInvalid(io::Error::new(
io::ErrorKind::InvalidInput,
"could not resolve to any addresses",
));
for target in targets {
match self
.connection_handle
.channel_open_direct_tcpip(
target.ip().to_string(),
target.port().into(),
src.0.clone(),
src.1,
)
.await
{
Ok(channel) => return Ok(channel),
Err(err) => connect_err = super::Error::SshError(err),
}
}
Err(connect_err)
}
/// Upload a file with sftp to the remote server.
///
/// `src_file_path` is the path to the file on the local machine.
/// `dest_file_path` is the path to the file on the remote machine.
/// Some sshd_config does not enable sftp by default, so make sure it is enabled.
/// A config line like a `Subsystem sftp internal-sftp` or
/// `Subsystem sftp /usr/lib/openssh/sftp-server` is needed in the sshd_config in remote machine.
pub async fn upload_file<T: AsRef<Path>, U: Into<String>>(
&self,
src_file_path: T,
//fa993: This cannot be AsRef<Path> because of underlying lib constraints as described here
//https://github.com/AspectUnk/russh-sftp/issues/7#issuecomment-1738355245
dest_file_path: U,
) -> Result<(), super::Error> {
// start sftp session
let channel = self.get_channel().await?;
channel.request_subsystem(true, "sftp").await?;
let sftp = SftpSession::new(channel.into_stream()).await?;
// read file contents locally
let file_contents = tokio::fs::read(src_file_path)
.await
.map_err(super::Error::IoError)?;
// interaction with i/o
let mut file = sftp
.open_with_flags(
dest_file_path,
OpenFlags::CREATE | OpenFlags::TRUNCATE | OpenFlags::WRITE | OpenFlags::READ,
)
.await?;
file.write_all(&file_contents)
.await
.map_err(super::Error::IoError)?;
file.flush().await.map_err(super::Error::IoError)?;
file.shutdown().await.map_err(super::Error::IoError)?;
Ok(())
}
/// Download a file from the remote server using sftp.
///
/// `remote_file_path` is the path to the file on the remote machine.
/// `local_file_path` is the path to the file on the local machine.
/// Some sshd_config does not enable sftp by default, so make sure it is enabled.
/// A config line like a `Subsystem sftp internal-sftp` or
/// `Subsystem sftp /usr/lib/openssh/sftp-server` is needed in the sshd_config in remote machine.
pub async fn download_file<T: AsRef<Path>, U: Into<String>>(
&self,
remote_file_path: U,
local_file_path: T,
) -> Result<(), super::Error> {
// start sftp session
let channel = self.get_channel().await?;
channel.request_subsystem(true, "sftp").await?;
let sftp = SftpSession::new(channel.into_stream()).await?;
// open remote file for reading
let mut remote_file = sftp
.open_with_flags(remote_file_path, OpenFlags::READ)
.await?;
// read remote file contents
let mut contents = Vec::new();
remote_file.read_to_end(contents.as_mut()).await?;
// write contents to local file
let mut local_file = tokio::fs::File::create(local_file_path.as_ref())
.await
.map_err(super::Error::IoError)?;
local_file
.write_all(&contents)
.await
.map_err(super::Error::IoError)?;
local_file.flush().await.map_err(super::Error::IoError)?;
Ok(())
}
/// Upload a directory to the remote server using sftp recursively.
///
/// `local_dir_path` is the path to the directory on the local machine.
/// `remote_dir_path` is the path to the directory on the remote machine.
/// All files and subdirectories will be uploaded recursively.
pub async fn upload_dir<T: AsRef<Path>, U: Into<String>>(
&self,
local_dir_path: T,
remote_dir_path: U,
) -> Result<(), super::Error> {
let local_dir = local_dir_path.as_ref();
let remote_dir = remote_dir_path.into();
// Verify local directory exists
if !local_dir.is_dir() {
return Err(super::Error::IoError(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("Local directory does not exist: {local_dir:?}"),
)));
}
// Start SFTP session
let channel = self.get_channel().await?;
channel.request_subsystem(true, "sftp").await?;
let sftp = SftpSession::new(channel.into_stream()).await?;
// Create remote directory if it doesn't exist
let _ = sftp.create_dir(&remote_dir).await; // Ignore error if already exists
// Process directory recursively
self.upload_dir_recursive(&sftp, local_dir, &remote_dir)
.await?;
Ok(())
}
/// Helper function to recursively upload directory contents
#[allow(clippy::only_used_in_recursion)]
fn upload_dir_recursive<'a>(
&'a self,
sftp: &'a SftpSession,
local_dir: &'a Path,
remote_dir: &'a str,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), super::Error>> + Send + 'a>>
{
Box::pin(async move {
// Read local directory contents
let entries = tokio::fs::read_dir(local_dir)
.await
.map_err(super::Error::IoError)?;
let mut entries = entries;
while let Some(entry) = entries.next_entry().await.map_err(super::Error::IoError)? {
let path = entry.path();
let file_name = entry.file_name();
let file_name_str = file_name.to_string_lossy();
let remote_path = format!("{remote_dir}/{file_name_str}");
let metadata = entry.metadata().await.map_err(super::Error::IoError)?;
if metadata.is_dir() {
// Create remote directory and recurse
let _ = sftp.create_dir(&remote_path).await; // Ignore error if already exists
self.upload_dir_recursive(sftp, &path, &remote_path).await?;
} else if metadata.is_file() {
// Upload file
let file_contents = tokio::fs::read(&path)
.await
.map_err(super::Error::IoError)?;
let mut remote_file = sftp
.open_with_flags(
&remote_path,
OpenFlags::CREATE | OpenFlags::TRUNCATE | OpenFlags::WRITE,
)
.await?;
remote_file
.write_all(&file_contents)
.await
.map_err(super::Error::IoError)?;
remote_file.flush().await.map_err(super::Error::IoError)?;
remote_file
.shutdown()
.await
.map_err(super::Error::IoError)?;
}
}
Ok(())
})
}
/// Download a directory from the remote server using sftp recursively.
///
/// `remote_dir_path` is the path to the directory on the remote machine.
/// `local_dir_path` is the path to the directory on the local machine.
/// All files and subdirectories will be downloaded recursively.
pub async fn download_dir<T: AsRef<Path>, U: Into<String>>(
&self,
remote_dir_path: U,
local_dir_path: T,
) -> Result<(), super::Error> {
let local_dir = local_dir_path.as_ref();
let remote_dir = remote_dir_path.into();
// Start SFTP session
let channel = self.get_channel().await?;
channel.request_subsystem(true, "sftp").await?;
let sftp = SftpSession::new(channel.into_stream()).await?;
// Create local directory if it doesn't exist
tokio::fs::create_dir_all(local_dir)
.await
.map_err(super::Error::IoError)?;
// Process directory recursively
self.download_dir_recursive(&sftp, &remote_dir, local_dir)
.await?;
Ok(())
}
/// Helper function to recursively download directory contents
#[allow(clippy::only_used_in_recursion)]
fn download_dir_recursive<'a>(
&'a self,
sftp: &'a SftpSession,
remote_dir: &'a str,
local_dir: &'a Path,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), super::Error>> + Send + 'a>>
{
Box::pin(async move {
// Read remote directory contents
let entries = sftp.read_dir(remote_dir).await?;
for entry in entries {
let name = entry.file_name();
let metadata = entry.metadata();
// Skip . and .. (already handled by iterator)
if name == "." || name == ".." {
continue;
}
let remote_path = format!("{remote_dir}/{name}");
let local_path = local_dir.join(&name);
if metadata.file_type().is_dir() {
// Create local directory and recurse
tokio::fs::create_dir_all(&local_path)
.await
.map_err(super::Error::IoError)?;
self.download_dir_recursive(sftp, &remote_path, &local_path)
.await?;
} else if metadata.file_type().is_file() {
// Download file
let mut remote_file =
sftp.open_with_flags(&remote_path, OpenFlags::READ).await?;
let mut contents = Vec::new();
remote_file.read_to_end(&mut contents).await?;
tokio::fs::write(&local_path, contents)
.await
.map_err(super::Error::IoError)?;
}
}
Ok(())
})
}
/// Execute a remote command via the ssh connection.
///
/// Returns stdout, stderr and the exit code of the command,
/// packaged in a [`CommandExecutedResult`] struct.
/// If you need the stderr output interleaved within stdout, you should postfix the command with a redirection,
/// e.g. `echo foo 2>&1`.
/// If you dont want any output at all, use something like `echo foo >/dev/null 2>&1`.
///
/// Make sure your commands don't read from stdin and exit after bounded time.
///
/// Can be called multiple times, but every invocation is a new shell context.
/// Thus `cd`, setting variables and alike have no effect on future invocations.
pub async fn execute(&self, command: &str) -> Result<CommandExecutedResult, super::Error> {
let mut stdout_buffer = vec![];
let mut stderr_buffer = vec![];
let mut channel = self.connection_handle.channel_open_session().await?;
channel.exec(true, command).await?;
let mut result: Option<u32> = None;
// While the channel has messages...
while let Some(msg) = channel.wait().await {
//dbg!(&msg);
match msg {
// If we get data, add it to the buffer
russh::ChannelMsg::Data { ref data } => {
stdout_buffer.write_all(data).await.unwrap()
}
russh::ChannelMsg::ExtendedData { ref data, ext } => {
if ext == 1 {
stderr_buffer.write_all(data).await.unwrap()
}
}
// If we get an exit code report, store it, but crucially don't
// assume this message means end of communications. The data might
// not be finished yet!
russh::ChannelMsg::ExitStatus { exit_status } => result = Some(exit_status),
// We SHOULD get this EOF messagge, but 4254 sec 5.3 also permits
// the channel to close without it being sent. And sometimes this
// message can even precede the Data message, so don't handle it
// russh::ChannelMsg::Eof => break,
_ => {}
}
}
// If we received an exit code, report it back
if let Some(result) = result {
Ok(CommandExecutedResult {
stdout: String::from_utf8_lossy(&stdout_buffer).to_string(),
stderr: String::from_utf8_lossy(&stderr_buffer).to_string(),
exit_status: result,
})
// Otherwise, report an error
} else {
Err(super::Error::CommandDidntExit)
}
}
/// A debugging function to get the username this client is connected as.
pub fn get_connection_username(&self) -> &String {
&self.username
}
/// A debugging function to get the address this client is connected to.
pub fn get_connection_address(&self) -> &SocketAddr {
&self.address
}
pub async fn disconnect(&self) -> Result<(), super::Error> {
self.connection_handle
.disconnect(russh::Disconnect::ByApplication, "", "")
.await
.map_err(super::Error::SshError)
}
pub fn is_closed(&self) -> bool {
self.connection_handle.is_closed()
}
}
impl Debug for Client {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Client")
.field("username", &self.username)
.field("address", &self.address)
.field("connection_handle", &"Handle<ClientHandler>")
.finish()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CommandExecutedResult {
/// The stdout output of the command.
pub stdout: String,
/// The stderr output of the command.
pub stderr: String,
/// The unix exit status (`$?` in bash).
pub exit_status: u32,
}
#[derive(Debug, Clone)]
struct ClientHandler {
hostname: String,
host: SocketAddr,
server_check: ServerCheckMethod,
}
impl Handler for ClientHandler {
type Error = super::Error;
async fn check_server_key(
&mut self,
server_public_key: &russh::keys::PublicKey,
) -> Result<bool, Self::Error> {
match &self.server_check {
ServerCheckMethod::NoCheck => Ok(true),
ServerCheckMethod::PublicKey(key) => {
let pk = russh::keys::parse_public_key_base64(key)
.map_err(|_| super::Error::ServerCheckFailed)?;
Ok(pk == *server_public_key)
}
ServerCheckMethod::PublicKeyFile(key_file_name) => {
let pk = russh::keys::load_public_key(key_file_name)
.map_err(|_| super::Error::ServerCheckFailed)?;
Ok(pk == *server_public_key)
}
ServerCheckMethod::KnownHostsFile(known_hosts_path) => {
let result = russh::keys::check_known_hosts_path(
&self.hostname,
self.host.port(),
server_public_key,
known_hosts_path,
)
.map_err(|_| super::Error::ServerCheckFailed)?;
Ok(result)
}
ServerCheckMethod::DefaultKnownHostsFile => {
let result = russh::keys::check_known_hosts(
&self.hostname,
self.host.port(),
server_public_key,
)
.map_err(|_| super::Error::ServerCheckFailed)?;
Ok(result)
}
}
}
}
// Tests removed as they depend on external test infrastructure
// Original tests are available in references/async-ssh2-tokio/src/client.rs