You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python SSHClient完整读取远程服务器文件到本地?

问题根因

你遇到的传输中断本质是paramiko默认会话超时、服务器侧闲置会话切断策略导致的,手动加sleep属于无效操作,反而会提升会话闲置断开的概率,仅在极少数场景下偶然生效。


方案1:直接读取远程文件末尾内容(优先推荐)

你仅需要文件末尾内容的场景下,完全不需要下载全量文件,通过SSH执行远程tail命令直接获取结果,传输效率提升10倍以上,完全规避传输中断问题:

import paramiko

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接时显式配置超时参数,避免连接阶段断开
client.connect(
    drasclientip,
    username=def_users[i],
    key_filename=pem_file,
    timeout=30,
    banner_timeout=20
)

# 按需调整末尾行数,示例取最后200行
tail_line_count = 200
command = f"tail -n {tail_line_count} {remote_file}"
stdin, stdout, stderr = client.exec_command(command)

# 读取输出和错误信息
file_end_content = stdout.read().decode("utf-8")
exec_err = stderr.read().decode("utf-8")

if exec_err:
    # 可自行扩展错误处理逻辑,比如文件不存在、权限不足等场景
    print(f"命令执行错误:{exec_err}")
else:
    # 结果写入本地文件或直接处理
    with open(file_dst, "w", encoding="utf-8") as f:
        f.write(file_end_content)

client.close()

方案2:优化SFTP全量传输逻辑

如果有全量下载文件的需求,按以下逻辑修改代码即可解决传输中断问题:

  • 连接阶段显式配置各类超时参数,避免无配置默认超时断开
  • 调整SFTP通道超时与窗口大小,提升传输稳定性与速度
  • 增加文件完整性校验,避免静默传输失败
import paramiko
import os

def check_transfer_complete(local_path, remote_path, sftp_client):
    """校验本地与远程文件大小一致,确认传输完整"""
    local_file_size = os.path.getsize(local_path)
    remote_file_size = sftp_client.stat(remote_path).st_size
    return local_file_size == remote_file_size

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(
    drasclientip,
    username=def_users[i],
    key_filename=pem_file,
    timeout=60,
    banner_timeout=30,
    auth_timeout=30
)

sftp = client.open_sftp()
# 配置SFTP通道超时,提升大文件传输稳定性
sftp.get_channel().settimeout(120)
# 不要手动给get方法传第三个参数为None,不需要回调就不传
sftp.get(remote_file, file_dst)

if check_transfer_complete(file_dst, remote_file, sftp):
    print("文件传输成功,内容完整")
else:
    print("文件传输不完整,可触发重试逻辑")

sftp.close()
client.close()

内容的提问来源于stack exchange,提问作者Anil Gadiyar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 00:15:03