75 lines
2.0 KiB
Rust
75 lines
2.0 KiB
Rust
// use openssh::{Session, KnownHosts};
|
|
use openssh::*;
|
|
// use std::io;
|
|
// use std::process::Stdio;
|
|
use tokio::io::{AsyncWriteExt,AsyncReadExt};
|
|
|
|
/// ssh
|
|
/// ````rust
|
|
/// // Prepare address
|
|
/// let host= String::from("hostname-or-ip");
|
|
/// let user= String::from("root");
|
|
/// let port: u16 = 22;
|
|
/// let addr = format!("ssh://{}@{}:{}",&user,&host,port);
|
|
///
|
|
/// // for scp_to_add data content into /tmp/hola
|
|
/// let task= String::from("scp_to_add");
|
|
/// let trgt=String::from("/tmp/hola");
|
|
/// let mut data = String::from("Dime \n");
|
|
//
|
|
/// // for ssh ls /tmp
|
|
/// let task= String::from("ssh");
|
|
/// let trgt=String::from("ls");
|
|
/// let mut data = String::from("/tmp");
|
|
///
|
|
/// // Call command and "macth" result
|
|
/// match cmds::ssh(&task, &addr, &trgt, &mut data) {
|
|
/// Ok(rs) => println!("ssh res: {:?} -> {:?}", rs, &data),
|
|
/// Err(e) => println!("ssh error: {:?}", e),
|
|
/// }
|
|
/// ```
|
|
// #[tokio::main]
|
|
pub async fn ssh(task: &str, addr: &str, trgt: &str, data: &mut String ) -> anyhow::Result<()> {
|
|
|
|
let session = Session::connect(&addr,KnownHosts::Strict).await?;
|
|
|
|
if task == "ssh" {
|
|
let ls = session.command(trgt).arg(data).output().await?;
|
|
match String::from_utf8(ls.stdout) {
|
|
Ok(res) => println!("ls : {:?}",&res),
|
|
Err(e) => println!("Error {:?}",e),
|
|
};
|
|
} else {
|
|
let mut sftp = session.sftp();
|
|
match task {
|
|
"scp_to" => {
|
|
let mut w = sftp.write_to(trgt).await?;
|
|
let content = data.as_bytes();
|
|
w.write_all(content).await?;
|
|
w.close().await?;
|
|
},
|
|
"scp_to_add" => {
|
|
let mut w = sftp.append_to(trgt).await?;
|
|
let content = data.as_bytes();
|
|
w.write_all(content).await?;
|
|
w.close().await?;
|
|
},
|
|
"scp_from" => {
|
|
let mut r = sftp.read_from(trgt).await?;
|
|
r.read_to_string(data).await?;
|
|
// println!("source: {:?}",&data);
|
|
r.close().await?;
|
|
},
|
|
_ => println!("Undefined {:?}",&task),
|
|
}
|
|
}
|
|
|
|
session.close().await?;
|
|
Ok(())
|
|
}
|
|
// println!("SSH error no KeyPair found");
|
|
// .map_err(|e| {
|
|
// debug!("e = {:?}", e);
|
|
// Error::SendError
|
|
// })?;
|