Python Network Programming 简明教程

Python - SFTP

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

SFTP is also known as the SSH File Transfer Protocol. It is a network protocol that provides file access, file transfer, and file management over any reliable data stream. The program is run over a secure channel, such as SSH, that the server has already authenticated the client, and that the identity of the client user is available to the protocol.

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

The pysftp module is a simple interface to SFTP. The module offers high level abstractions and task based routines to handle the SFTP needs. So we install the module into our python environment with the below command.

pip install pysftp

Example

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

In the below example we login to a remote server using sftp and then get and put some file in that directory.

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 目录中存在的文件的列表,还可以在该目录中放置和获取一些文件。

When we run the above code we are able to see the list of files present in the allcode directory and also put and get some file in that directory.