我正在尝试将 telnet 命令与 ansible Expect 模块一起使用来推送初始配置,但它不起作用,我怀疑问题出在响应部分,这是我的剧本:
- hosts: wired
gather_facts: false
connection: local
tasks:
- name: telnet,login and execute command
ignore_errors: no
expect:
command: telnet "{{ inventory_hostname }}" 2009
responses:
.*>: "enable"
.*Password: "mainpass"
.*#: "show runn | in hostname"
register: telnet_output
- name: Debug output
debug: var=telnet_output.stdout_lines
当我尝试从终端远程登录时,我得到以下信息:
Trying 10.1.1.1...
Connected to switch.lab.local.
Escape character is '^]'.
我需要按 Enter 键,然后我会看到:
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
To log in to this device, use the following password/credentials:
enable password mainpass
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
switch>
然后我必须输入命令启用,系统会提示输入启用密码:
switch>enable
Password:
switch#
我无法将上面的内容翻译到我的剧本中的响应部分,当我运行它时,我看到这个:
fatal: [switch]: FAILED! => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": true,
"cmd": "telnet \"switch\" 2009",
"delta": "0:00:00.312863",
"end": "2022-11-08 15:01:27.707396",
"invocation": {
"module_args": {
"chdir": null,
"command": "telnet \"switch\" 2009",
"creates": null,
"echo": false,
"removes": null,
"responses": {
".*#": "show runn | in hostname",
".*>": "enable",
".*Password": "mainpass",
"Trying 10.1.1.1....*": "\n",
"telnet: Unable to connect to remote host: Connection refused": ""
},
"timeout": 30
}
},
"msg": "non-zero return code",
"rc": 1,
"start": "2022-11-08 15:01:27.394533",
"stdout": "Trying 10.1.1.1...\r\ntelnet: Unable to connect to remote host: Connection refused",
"stdout_lines": [
"Trying 10.1.1.1...",
"telnet: Unable to connect to remote host: Connection refused"
]
}
答案1
由于您看到 Connection Refused 消息,我认为 Ansible 连接没有像您期望/希望的那样工作。 Ansible 构建了特殊的模块来处理网络设备,请参见此处:https://docs.ansible.com/ansible/latest/network/getting_started/network_differences.html
我认为您最好的选择是阅读这些文档以了解如何进行设置。此外,telnet 以纯文本形式通过线路传输,因此如果设备支持,您确实应该升级到 SSH 或 HTTPS API。