0

我正在为 Ansible 2.5 开发 RouterOS 网络模块。

RouterOS shell 可以打印一些应该在on_open_shell()事件中检测到并自动跳过或关闭的消息。这些Do you want to see the software license? [Y/n]:和其他一些,所有这些都在 MikroTik Wiki中有详细记录。

这是我的做法:

def on_open_shell(self):
    try:
        if not prompt.strip().endswith(b'>'):
            self._exec_cli_command(b' ')
    except AnsibleConnectionFailure:
        raise AnsibleConnectionFailure('unable to bypass license prompt')

它确实绕过了许可证提示。\n然而,RouterOS 设备的响应似乎是对随后实际命令的响应。所以,如果我的剧本中有两个这样的任务:

---
- hosts: routeros
  gather_facts: no
  connection: network_cli
  tasks:
    - routeros_command:
        commands:
          - /system resource print
          - /system routerboard print
      register: result

    - name: Print result
      debug: var=result.stdout_lines

这是我得到的输出:

ok: [example] => {
    "result.stdout_lines": [
        [
            ""
        ],
        [
            "uptime: 12h33m29s",
            "                  version: 6.42.1 (stable)",
            "               build-time: Apr/23/2018 10:46:55",
            "              free-memory: 231.0MiB",
            "             total-memory: 249.5MiB",
            "                      cpu: Intel(R)",
            "                cpu-count: 1",
            "            cpu-frequency: 2700MHz",
            "                 cpu-load: 2%",
            "           free-hdd-space: 943.8MiB",
            "          total-hdd-space: 984.3MiB",
            "  write-sect-since-reboot: 7048",
            "         write-sect-total: 7048",
            "        architecture-name: x86",
            "               board-name: x86",
            "                 platform: MikroTik"
        ]
    ]
}

如您所见,输出似乎偏移了 1。我应该怎么做才能纠正这个问题?

4

1 回答 1

1

事实证明,问题出在定义 shell 提示符的正则表达式中。我是这样定义的:

terminal_stdout_re = [
    re.compile(br"\[\w+\@[\w\-\.]+\] ?>"),
    # other cases
]

它与提示符的结尾不匹配,导致 Ansible 认为在实际命令输出之前有一个换行符。这是正确的正则表达式:

terminal_stdout_re = [
    re.compile(br"\[\w+\@[\w\-\.]+\] ?> ?$"),
    # other cases
]
于 2018-06-01T15:54:31.063 回答