rust使用ssh2进行远程访问与文件读写


 

use std::net::TcpStream;
use ssh2::Session;
use std::io::prelude::*;
use std::path::Path;

fn main() {
    let tcp = TcpStream::connect("121.37.18.151:22").unwrap();
    let mut sess = Session::new().unwrap();
    sess.set_tcp_stream(tcp);
    sess.handshake().unwrap();
    
    sess.userauth_password("myname","mypassword");
    assert!(sess.authenticated());

    let mut channel = sess.channel_session().unwrap();
    channel.exec("ls").unwrap();
    let mut s = String::new();
    channel.read_to_string(&mut s).unwrap();
    println!("{}",s);
    channel.wait_close();
    println!("{}",channel.exit_status().unwrap());
    //
    let mut remote_file = sess.scp_send(Path::new("1.txt"),0o644,10,None).unwrap();
    remote_file.write(b"0123456789").unwrap();
 

    let (mut remote_file,stat) = sess.scp_recv(Path::new("1.txt")).unwrap();
    let mut contents = Vec::new();
    remote_file.read_to_end(&mut contents).unwrap();
    println!("{:?}",contents);
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM