深度阅读

How to use SFTP in Python

作者
作者
2023年08月22日
更新时间
14.19 分钟
阅读时间
0
阅读量

To use SFTP in Python, you can use the pysftp library or the paramiko library. Here’s an example of how to use pysftp to connect to an SFTP server, list its contents, and download a file:

import pysftp

# Set up the connection parameters
host = 'example.com'
username = 'myusername'
password = 'mypassword'
remote_path = '/remote/path/'

# Connect to the SFTP server and list its contents
with pysftp.Connection(host, username=username, password=password) as sftp:
    with sftp.cd(remote_path):
        directory_structure = sftp.listdir_attr()
        for attr in directory_structure:
            print(attr.filename)

    # Download a file from the SFTP server
    sftp.get('filename.txt')

Alternatively, you can use paramiko to accomplish the same tasks:

import paramiko

# Set up the connection parameters
host = 'example.com'
username = 'myusername'
password = 'mypassword'
remote_path = '/remote/path/'

# Connect to the SFTP server
with paramiko.Transport((host, 22)) as transport:
    transport.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(transport)

    # List the contents of the remote directory
    directory_structure = sftp.listdir_attr(remote_path)
    for attr in directory_structure:
        print(attr.filename)

    # Download a file from the SFTP server
    sftp.get(remote_path + 'filename.txt', 'local_filename.txt')

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。