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

Ansible通过Mikrotik堡垒机连接本地交换机报错求助

解决Ansible通过RouterOS堡垒机连接NAT后设备的SSH报错问题

问题背景

在Debian客户端使用Ansible,通过RouterOS SSH堡垒机jumphost连接NAT后的RouterOS交换机localswitch,执行playbook获取设备版本时,出现报错:

"msg": "ssh connection failed: ssh connect failed: Socket error: Connection reset by peer"

现有配置如下:

inventory.yaml

all:
  switches:
    hosts:
      localswitch.company.local:
        vars:
          ansible_ssh_common_args: '-o ProxyCommand="ssh -W %h:%p -q myuser@jumphost.company.com"'

playbook.yaml

- hosts: all
  connection: network_cli
  gather_facts: true
  vars:
    ansible_network_os: routeros
  tasks:
    - name: Print RouterBoard version
      routeros_command:
        commands:
          - /system routerboard print
      register: result

    - name: Display command output
      debug: 
        var: result.stdout_lines

问题原因

RouterOS的SSH实现与标准OpenSSH存在差异,不支持-W参数,而原配置中使用了该参数进行代理转发,导致连接被重置。

解决方案

1. 修改ProxyCommand适配RouterOS

将ansible_ssh_common_args中的代理命令替换为使用nc(netcat)转发流量,这是RouterOS支持的方式。同时移除不必要的HTML转义符",确保YAML格式正确。

修改后的inventory.yaml:

all:
  switches:
    hosts:
      localswitch.company.local:
        vars:
          ansible_ssh_common_args: '-o ProxyCommand=ssh myuser@jumphost.company.com nc %h %p'
          ansible_user: YOUR_LOCALSWITCH_USER  # 替换为localswitch的SSH用户名
          ansible_password: YOUR_LOCALSWITCH_PASS  # 若使用密码登录,替换为对应密码

2. 前置检查

  • 确保Debian客户端能直接SSH登录jumphost.company.com
  • 确保jumphost上已安装nc(RouterOS默认可能未包含,可通过/tool fetch下载或系统包管理安装)
  • 手动测试代理连接是否成功,在Debian终端执行:
ssh -o ProxyCommand='ssh myuser@jumphost.company.com nc %h %p' YOUR_LOCALSWITCH_USER@localswitch.company.local

若能成功登录localswitch,说明代理配置有效。

3. 可选:使用ProxyJump(需OpenSSH 7.3+)

如果你的Debian客户端使用的OpenSSH版本在7.3以上,且jumphost的RouterOS SSH支持该特性,可以简化配置为:

ansible_ssh_common_args: '-o ProxyJump=myuser@jumphost.company.com'

验证

修改配置后,重新运行playbook:

ansible-playbook -i inventory.yaml playbook.yaml

此时应能成功连接localswitch并获取RouterBoard版本信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 07:17:39