Python 快速实现 FTP 服务器

2017-2-16 杜世伟 Python

有时当你想快速搭建一个 FTP 服务器来临时实现文件上传下载时,这是特别有用的。我们这里利用 Python 的 Pyftpdlib 模块可以快速的实现一个 FTP 服务器的功能。

首先安装 Pyftpdlib 模块

$ sudo pip install pyftpdlib
The directory '/Users/xiaodu/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/xiaodu/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting pyftpdlib
Installing collected packages: pyftpdlib
Successfully installed pyftpdlib-1.5.3

通过 Python 的 -m 选项将 Pyftpdlib 模块作为一个简单的独立服务器来运行,假设我们需要共享目录 /Users/Mike/Docker,只需要以下这个命令行就可以轻松实现:

$ cd /Users/xiaodu/python/test
[I 2017-02-15 23:14:20] >>> starting FTP server on :::2121, pid=1165 <<<
[I 2017-02-15 23:14:20] concurrency model: async
[I 2017-02-15 23:14:20] masquerade (NAT) address: None
[I 2017-02-15 23:14:20] passive ports: None
至此一个简单的 FTP 服务器已经搭建完成,访问 ftp://IP:PORT 即可。例如类似下面的 URL:

ftp://192.168.199.206:2121
默认 IP 为本机所有可用 IP,端口为 2121。
默认登陆方式为匿名。
默认权限是只读。
如果你要建一个有认证且可写的 FTP 服务器,可使用类似以下指令:

$ python -m pyftpdlib -i 192.168.199.206 -w -d /tmp/ -u xiaodu -P 123456
小插曲:测试时一直使用密码 000000 这样的弱密码做认证密码,在客户端登陆时一直提示认证失败。看来 Pyftpdlib 模块还做了基本的安全策略哟,不错的!

常用可选参数说明:

-i 指定IP地址(默认为本机所有可用 IP 地址)
-p 指定端口(默认为 2121)
-w 写权限(默认为只读)
-d 指定目录 (默认为当前目录)
-u 指定登录用户名
-P 指定登录密码
更多参数可以使用以下指令查询:

$ python -m pyftpdlib --help

Usage: python -m pyftpdlib [options]

Start a stand alone anonymous FTP server.

Options:
-h, --help
show this help message and exit

-i ADDRESS, --interface=ADDRESS
specify the interface to run on (default all interfaces)

-p PORT, --port=PORT
specify port number to run on (default 2121)

-w, --write
grants write access for logged in user (default read-only)

-d FOLDER, --directory=FOLDER
specify the directory to share (default current directory)

-n ADDRESS, --nat-address=ADDRESS
the NAT address to use for passive connections

-r FROM-TO, --range=FROM-TO
the range of TCP ports to use for passive connections (e.g. -r 8000-9000)

-D, --debug
enable DEBUG logging evel

-v, --version
print pyftpdlib version and exit

-V, --verbose
activate a more verbose logging

-u USERNAME, --username=USERNAME
specify username to login with (anonymous login will be disabled and password required if supplied)

-P PASSWORD, --password=PASSWORD
specify a password to login with (username required to be useful)
如果你需卸载 Pyftpdlib 模块,可以通过以下命令:

$ pip uninstall pyftpdlib

具体的可以参看:https://code.google.com/p/pyftpdlib/wiki/Tutorial

标签: python ftp pyftpdlib

Powered by emlog 沪ICP备2023034538号-1