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

Netmiko调用SCPConn传输文件时触发Socket is closed异常

Netmiko SCP传输触发"Socket is closed"异常排查修复方案

问题对应复现代码

# ---- Connect to the device
session = ConnectHandler(device_type=device_type, ip=device['ipaddr'],
                         username=creds[0], password=creds[1])

net_connect = session

#transferring file to device

net_connect.config_mode ( )
net_connect.send_command ( 'ip scp server enable' )
scp_conn = SCPConn ( net_connect )
s_file = file_s
d_file = file_s
scp_conn.scp_transfer_file ( s_file , d_file )

核心根因与修复

最常见触发原因是开启SCP服务后未退出配置模式:90%以上的网络设备不允许在全局配置模式下建立SCP传输通道,设备收到SCP握手请求时会主动断开SSH连接,直接抛出Socket关闭异常。
修复逻辑:执行完SCP开启命令后必须退回特权EXEC模式,清空通道残留缓存后再建立SCP连接,修复后代码如下:

# ---- Connect to the device
session = ConnectHandler(
    device_type=device_type, 
    ip=device['ipaddr'],
    username=creds[0], 
    password=creds[1],
    # 新增超时配置,避免大文件传输时连接提前断开
    conn_timeout=30,
    banner_timeout=30,
    auth_timeout=30,
    timeout=120,
    global_delay_factor=2
)
net_connect = session

# 开启设备端SCP服务
net_connect.config_mode()
net_connect.send_command('ip scp server enable')
# 关键操作:退出配置模式回到特权模式
net_connect.exit_config_mode()
# 清空通道内残留的命令回显、弹窗日志,避免干扰SCP握手
net_connect.clear_buffer()

# 实例化SCP对象执行传输
scp_conn = SCPConn(net_connect)
s_file = file_s
d_file = file_s
scp_conn.scp_transfer_file(s_file, d_file)
# 传输完成后关闭SCP通道
scp_conn.close()

其他高频问题排查

  • 设备侧配置校验:手动SSH登录设备,直接测试SCP上传功能,确认以下配置项正确:
    • 开启ip scp server enable后配置已生效,部分设备需要配套配置VTY线路放行SCP、AAA授权为当前登录用户开放SCP权限
    • 思科类设备需要确保登录用户权限等级为15,华为/H3C类设备需要确保用户有network-admin或对应文件操作权限
    • 确认设备目标存储路径(如flash:、bootflash:)剩余空间足够,空间不足时设备也会主动断开SCP连接
  • 替换为官方封装的传输方法:手动调用SCPConn需要自行处理模式切换、通道校验逻辑,出错率高,可直接使用Netmiko内置的file_transfer方法,内部自动完成所有前置操作,示例:
from netmiko import file_transfer
transfer_result = file_transfer(
    net_connect,
    source_file=file_s,
    dest_file=file_s,
    file_system='flash:',  # 替换为设备实际存储路径
    direction='put',
    overwrite_file=True
)
  • 异常定位辅助:开启Netmiko debug日志,查看Socket断开前的最后交互报文,直接定位断连发起方:
import logging
logging.basicConfig(level=logging.DEBUG)
netmiko_logger = logging.getLogger("netmiko")

如果日志显示SCP握手阶段收到设备返回的权限拒绝、模式错误类报文,直接对应排查设备侧配置即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 11:18:08