rust 如何将文件上传到sftp服务器

iibxawm4  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(265)

如何使用rust将文件上传到sftp。
这是我找到的唯一有用的链接:openssh_sftp_client。但是,围绕该库的使用的文档很少,这使得使用该库非常困难
注意:我不是在谈论使用cli(如sftprftp)上传到sftp
我尝试了两个板条箱ssh2rust-ftp,但出现错误:
ssh2:

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

// Connect to the local SSH server
let tcp = TcpStream::connect("SFTP_IP:PORT").unwrap();
let mut sess = Session::new().unwrap();
sess.set_tcp_stream(tcp);
sess.handshake().unwrap();
sess.userauth_agent("username").unwrap();

// Write the file
let mut remote_file = sess.scp_send(Path::new("remote"),
                                    0o644, 10, None).unwrap();
remote_file.write(b"1234567890").unwrap();
// Close the channel and wait for the whole content to be tranferred
remote_file.send_eof().unwrap();
remote_file.wait_eof().unwrap();
remote_file.close().unwrap();
remote_file.wait_close().unwrap();

错误:

rust-ftp:

use std::str;
use std::io::Cursor;
use ftp::FtpStream;

fn main() {
    // Create a connection to an FTP server and authenticate to it.
    let mut ftp_stream = FtpStream::connect("SFTP_IP:PORT").unwrap();
    let _ = ftp_stream.login("username", "password").unwrap();

    // Get the current directory that the client will be reading from and writing to.
    println!("Current directory: {}", ftp_stream.pwd().unwrap());

    // Change into a new directory, relative to the one we are currently in.
    let _ = ftp_stream.cwd("test_data").unwrap();

    // Retrieve (GET) a file from the FTP server in the current working directory.
    let remote_file = ftp_stream.simple_retr("ftpext-charter.txt").unwrap();
    println!("Read file with contents\n{}\n", str::from_utf8(&remote_file.into_inner()).unwrap());

    // Store (PUT) a file from the client to the current working directory of the server.
    let mut reader = Cursor::new("Hello from the Rust \"ftp\" crate!".as_bytes());
    let _ = ftp_stream.put("greeting.txt", &mut reader);
    println!("Successfully wrote greeting.txt");

    // Terminate the connection to the server.
    let _ = ftp_stream.quit();
}

错误:

fnx2tebb

fnx2tebb1#

我已经设法找到了一个变通办法,但这并不理想。
而不是在本地创建一个文件,然后上载到sftp,我是直接在sftp中写文件。

use std::net::TcpStream;
use ssh2::Session;
use std::path::Path;

let tcp = TcpStream::connect("IP:PORT")).unwrap();
let mut sess = Session::new().unwrap();
sess.set_tcp_Stream(tcp);
sess.handshake().unwrap();
sess.userauth_password("USER", "PSWD").unwrap();

let sftp = sess.sftp().unwrap();

sftp.mkdir(Path::new("path/to/sftp/dir"), 0o777).ok();
sftp.create(&Path::new("path/to/file/in/sftp/dir/file.json"))
    .unwrap()
    .write_all("text to be written to file")
    .unwrap();

相关问题