通过Opengear远程控制台用Netmiko配置Cisco设备遇超时问题求助
问题描述
我们正通过Opengear远程连接Cisco设备的控制台端口,需要通过该端口下发配置,编写了如下代码:
from netmiko import ConnectHandler, redispatch device = { "device_type": "terminal_server", "ip": "****", "username": "****", "password": "****", "session_log": 'netmiko_session.log', "port": '22' } net_connect = ConnectHandler(**device) net_connect.write_channel("\r") net_connect.enable() net_connect.send_command_timing("enable") redispatch(net_connect, device_type="cisco_xe") output = net_connect.send_command("show version") print(output) net_connect.disconnect()
直接运行代码时出现错误,但使用PyCharm调试时却能正常运行。从设备控制台可见,调试模式下设备可激活并进入enable模式,直接运行则设备无响应,请问是否遗漏了什么配置?
错误信息
Traceback (most recent call last): File "C:\Users\user\venv\console_conn.py", line 24, in <module> redispatch(net_connect, device_type="cisco_xe") File "C:\Users\user\venv\lib\site-packages\netmiko\ssh_dispatcher.py", line 487, in redispatch obj._try_session_preparation() File "C:\Users\user\venv\lib\site-packages\netmiko\base_connection.py", line 963, in _try_session_preparation self.session_preparation() File "C:\Users\user\venv\lib\site-packages\netmiko\cisco\cisco_ios.py", line 19, in session_preparation self.set_terminal_width(command=cmd, pattern=cmd) File "C:\Users\user\lib\site-packages\netmiko\base_connection.py", line 1322, in set_terminal_width output = self.read_until_pattern(pattern=pattern) File "C:\Users\user\venv\lib\site-packages\netmiko\base_connection.py", line 721, in read_until_pattern raise ReadTimeout(msg) netmiko.exceptions.ReadTimeout: Pattern not detected: 'terminal width 511' in output. Things you might try to fix this: 1. Adjust the regex pattern to better identify the terminating string. Note, in many situations the pattern is automatically based on the network device's prompt. 2. Increase the read_timeout to a larger value. You can also look at the Netmiko session_log or debug log for more information.
解决方案
核心问题是直接运行时设备响应速度跟不上代码执行节奏,调试模式下的断点等待给了设备足够返回时间,因此能正常执行。可从以下几点调整:
增加延时匹配设备响应节奏
在write_channel("\r")后添加延时,确保设备返回提示符后再执行后续操作:import time net_connect.write_channel("\r") time.sleep(2) # 根据设备实际响应速度调整时长同时用
send_command_timing替代enable(),该方法基于时间等待而非严格匹配提示符,更适配终端服务器跳转场景:# 替换原有的net_connect.enable()和send_command_timing("enable") net_connect.send_command_timing("enable", delay_factor=2)确认会话状态后再执行redispatch
在redispatch前读取输出,确保已进入Cisco设备的enable模式:# 等待出现enable模式提示符(#) output = net_connect.read_until_pattern(pattern=r"#") # 再执行redispatch redispatch(net_connect, device_type="cisco_xe")解决终端宽度匹配超时问题
错误提示无法匹配terminal width 511,可手动提前设置终端宽度,或延长redispatch的等待时间:# 手动设置终端宽度 net_connect.send_command_timing("terminal width 511") # 或延长redispatch的读取超时时间 redispatch(net_connect, device_type="cisco_xe", read_timeout=30)检查终端服务器跳转命令
部分Opengear终端服务器需要执行跳转命令(如connect <端口号>)才能进入Cisco控制台,确认是否遗漏该步骤:# 示例:根据你的Opengear配置替换端口号 net_connect.send_command_timing("connect 1/1", delay_factor=3)
内容的提问来源于stack exchange,提问作者chun xu
相关产品推荐
相关产品推荐

