Python Network Programming 简明教程

Python - SFTP

SFTP 也称为 SSH 文件传输协议。它是一种网络协议,可在任何可靠的数据流上提供文件访问、文件传输和文件管理。该程序通过安全通道(如 SSH)运行,服务器已经对客户端进行了身份验证,并且可以将客户端用户的身份提供给协议。

pysftp 模块是 SFTP 的简单界面。该模块提供高级抽象和基于任务的例程来处理 SFTP 需求。因此,我们使用下面的命令将该模块安装到我们的 Python 环境中。

pip install pysftp

Example

在下面的示例中,我们使用 sftp 登录到远程服务器,然后在该目录中获取并放置一些文件。

import pysftp

with pysftp.Connection('hostname', username='me', password='secret') as sftp:

    with sftp.cd('/allcode'):           # temporarily chdir to allcode
        sftp.put('/pycode/filename')  	# upload file to allcode/pycode on remote
        sftp.get('remote_file')         # get a remote file

当我们运行上面的代码时,我们将能够看到 allcode 目录中存在的文件的列表,还可以在该目录中放置和获取一些文件。