使用pexpect登录Cisco路由器时无法识别--More--提示符的问题
解决Pexpect处理Cisco路由器--More--提示符的问题
嘿,我明白你遇到的麻烦了!Cisco设备的--More--提示符确实需要发送空格来继续翻页,你之前代码里发送反斜杠\肯定行不通。咱们直接来改代码解决这个问题:
核心问题修正
你需要把处理--More--时的发送指令从send('\')改成send(' ')——注意是单个空格字符,不要加换行。另外,最好用循环来处理所有的翻页提示,直到回到特权模式的#提示符。
完整示例代码
这里给你补全并修正后的代码,你可以参考调整:
import pexpect import sys import os import getpass hostname = "router-2" username = raw_input('Enter Your username: ') password = getpass.getpass('Password:') # 打开日志文件(用open比file更规范,Python 2/3都兼容) fout = open('agglog.txt','w') # 启动SSH连接到路由器 child = pexpect.spawn('ssh {}@{}'.format(username, hostname)) child.logfile = fout # 把交互日志写入文件 # 处理登录流程 child.expect('Username:') child.sendline(username) child.expect('Password:') child.sendline(password) # 假设你要执行一个长输出的命令,比如show running-config child.expect('#') # 等待特权模式提示符 child.sendline('show running-config') # 循环处理所有--More--提示 while True: # 同时监听--More--和特权模式#提示符 match_index = child.expect(['--More--', '#'], timeout=60) if match_index == 0: # 匹配到--More--,发送空格继续翻页 child.send(' ') else: # 回到特权模式,退出循环 break # 退出连接 child.sendline('exit') child.close() fout.close()
关键注意事项
- 不要用
sendline发送空格:sendline会自动在末尾加换行符,可能导致路由器执行空命令,用send(' ')就刚好是单个空格,符合Cisco的翻页要求。 - 循环处理翻页:长命令的输出会多次出现
--More--,用循环能自动处理完所有内容,不用手动写多次expect。 - 超时设置:如果命令输出很慢,可以给
expect加timeout参数(比如上面的60秒),避免超时报错。
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

