【每周一库】 rust-ftp - an FTP client written in Rust

时间:2022-07-23
本文章向大家介绍【每周一库】 rust-ftp - an FTP client written in Rust,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本期的每周一库带来的是Rust下的ftp client库:rust-ftp

相关链接

  • rust-ftp docs: https://docs.rs/ftp/3.0.1/ftp/
  • rust-ftp github: https://github.com/mattnenterprise/rust-ftp

rust-ftp的文档页面给出了使用的用例,从代码来看非常简单,下面我们通过实际使用来体验rust-ftp库。

开发环境

  • Windows 10
  • rustc --version: rustc 1.46.0-nightly (6bb3dbfc6 2020-06-22)
  • cargo --version: cargo 1.46.0-nightly (089cbb80b 2020-06-15)
  • rust-ftp version: 3.0.1

通过FileZilla Server来体验rust-ftp的功能

首先我们下载FileZilla Server作为本地的ftp服务器程序

这里简单赘述一下FileZilla Server的配置,启动FileZilla Server之后

配置FileZilla Server的User

在下图右侧窗口添加一个User,用户名设置为admin,密码设置为admin

配置FileZilla Server的共享文件夹

配置完User之后,我们需要告诉FileZilla Server共享的目录在哪里,本例中我们使用了目录D:TempftpShare目录,配置完成之后如下图,需要注意添加刚才创建的admin用户

使用rust-ftp和FileZilla Server搭建的本地ftp服务器进行文件读取和上传

经过上面的FileZilla Server的配置,我们在本地已经有了一个运行的ftp服务器,服务器的跟目录在本例中为D:TempftpShare目录

我们创建一个新的rust工程

cargo new hello-rustftp

在工程的Cargo.toml文件中添加引用

[dependencies]
ftp = { version="3.0.1"}

修改src/main.rs文件内容如下

extern crate ftp;

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

fn main() {
    println!("Hello rust-ftp!");
    // Create a connection to an FTP server and authenticate to it.
    let mut ftp_stream = FtpStream::connect("127.0.0.1:21").unwrap();
    let _ = ftp_stream.login("admin", "admin").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("rust.txt").unwrap();
    println!("Read file with contentsn{}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("hello-rustftp.txt", &mut reader);
    println!("Successfully upload hello-rustftp.txt");

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

上面的代码做了三件事

  • 使用用户名admin,密码admin(刚才在FileZella Server中配置的User身份)连接本地ftp服务器
  • 切换到本地ftp服务器目录的test_data目录读取其中名为rust.txt文件内容
  • 向ftp服务器目录的test_data目录写入一个名为hello-rustftp.txt文件,文件内容为Hello from the Rust "ftp" crate!

既然我们的rust程序要在ftp服务器跳转到目录test_data并读取其中的rust.txt文件,那么我们首先要在我们的ftp服务器中创建名为test_data的目录和rust.txt文件

其中我们向文件rust.txt文件中写入内容

ftp服务器根目录(本例中为:D:TempftpShare文件夹)的目录结构为:

到这里我们就配置完了本地ftp服务器的目录结构,我们可以运行我们的rust程序进行测试

使用命令cargo build编译工程,使用命令cargo run运行

同时我们的ftp服务器本地目录D:TempftpSharetest_data中会出现我们新上传的hello-rustftp.txt文件

到这里我们完成了rust-ftp库的简单使用。