Python SFTP


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

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

pip install pysftp

例子


在下面的示例中,我们使用 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 目录中存在的文件列表,并在该目录中放置和获取一些文件。