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

Ansible 2.5 RouterOS模块响应空字符串偏移问题求助

Fixing Command Output Offset in Ansible RouterOS Module

The issue here is that your current on_open_shell() implementation sends a space character (b' ') to bypass the license prompt, but this action generates an empty response that Ansible's network_cli connection treats as the output of your first actual command. That's why you're seeing the empty string in stdout_lines[0] and the first command's result shifted to the second position.

Here's how to fix it by directly handling the license prompt without introducing an extra empty response:

def on_open_shell(self):
    try:
        # Read the initial shell output to check for prompts
        current_output = self._connection.receive()
        
        # Detect and respond to the license prompt explicitly
        while b'Do you want to see the software license?' in current_output:
            # Send 'n' followed by newline to decline the license view
            self._connection.send(b'n\n')
            # Wait for the next output to confirm the prompt is cleared
            current_output = self._connection.receive()
        
        # Verify we've reached the valid RouterOS command prompt
        if not current_output.strip().endswith(b'>'):
            raise AnsibleConnectionFailure('Failed to reach RouterOS command prompt after bypassing license')
    except AnsibleConnectionFailure:
        raise AnsibleConnectionFailure('Unable to bypass license prompt or establish valid shell session')

Why this works:

  • Instead of sending a random space (which triggers an empty command execution), we explicitly respond to the license prompt with b'n\n'—this is the intended way to decline the license view, and RouterOS won't generate an extra empty command response for this action.
  • We use receive() and loop to ensure we fully handle the prompt before proceeding, making sure the shell is in a ready state (at the command prompt >) before any user commands are executed.

After applying this change, run your playbook again. You should see the correct output without offset:

ok: [example] => {
    "result.stdout_lines": [
        [ "uptime: 12h33m29s",
          " version: 6.42.1 (stable)",
          " build-time: Apr/23/2018 10:46:55",
          "...",
          " platform: MikroTik" ],
        [ "routerboard: yes",
          " model: RBxxxx",
          "...",
          " current-firmware: 6.42.1" ]
    ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:06:14