使用paramiko sftp下载写入文件

问题描述 投票:0回答:1

我正在使用 Paramiko 从 sftp 服务器获取文件。如何获取正在写入的文件(文件大小不断变化)

我尝试使用 sftp_connection.get(remotepath, localpath) 但无法下载文件。

paramiko
1个回答
0
投票

如果您使用 Paramiko 从 SFTP 服务器下载文件,并且该文件正在连续写入(例如,不断更新的日志文件),则可以使用 Paramiko 在写入时流式传输该文件。

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect(hostname, port, username, password)

sftp = ssh.open_sftp()

# Create a file object to write the downloaded content
with sftp.file(remote_path, 'r') as remote_file, open(local_path, 'wb') as local_file:
    # Stream the file while it's being written
    while True:
        data = remote_file.read(1024)  # Adjust the buffer size as needed
        if not data:
            break
        local_file.write(data)

# Close the SFTP connection
sftp.close()

# Close the SSH connection
ssh.close()

在脚本中,您使用循环不断从远程文件读取数据并将其写入本地文件,直到没有更多可用数据为止。

您可以根据您的具体用例调整缓冲区大小(本示例中为 1024)以优化性能。

© www.soinside.com 2019 - 2024. All rights reserved.