使用Paramiko传输文件时随机出现“Error reading SSH protocol banner”问题求助
可行解决方案
延长超时参数:
当前设置的banner_timeout=60可能不足以应对服务器处理特定大小文件时的延迟。尝试增大banner_timeout(比如设为120),同时调高连接timeout,避免连接阶段过早断开:ssh.connect(**self.config, timeout=30, banner_timeout=120)添加重试逻辑:
这类随机异常多由瞬时网络波动或服务器负载峰值导致,针对失败请求添加重试机制可有效规避:import time max_retries = 3 for attempt in range(max_retries): try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(**self.config, timeout=30, banner_timeout=120) with ssh.open_sftp() as sftp: sftp.put(local_path, remote_path) ssh.close() break except paramiko.SSHException as e: if attempt == max_retries - 1: raise e time.sleep(2) # 重试前短暂等待检查服务器SSH配置:
特定大小文件触发问题,可能和服务器SSH服务的连接限制有关。登录目标服务器,修改/etc/ssh/sshd_config中的以下参数,放宽连接阈值:MaxStartups 100:30:200 MaxSessions 100修改后重启sshd服务:
systemctl restart sshd优化SFTP传输缓冲区:
调整SFTP传输的缓冲区大小,减少单次传输的资源占用,避免触发服务器端的连接限制:with ssh.open_sftp() as sftp: # 设置缓冲区为1MB,可根据实际情况调整 sftp.put(local_path, remote_path, bufsize=1024*1024)
内容的提问来源于stack exchange,提问作者Vikas Sharma
相关产品推荐
相关产品推荐

