Python: SSH连接Cisco设备并运行show命令
我仔细看过这个帖子,还研究了Exscript、paramiko、Fabric和pxssh,但还是搞不懂 如何保持与Cisco路由器的SSH连接。我对Python脚本还很陌生。
我想写一个Python脚本,能够通过SSH连接到Cisco设备,运行“show version”命令,然后把结果显示在记事本里,最后结束这个脚本。
对于那些不需要用户与设备互动的显示命令,我能做到。例如:
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
account = read_login()
conn = SSH2()
conn.connect('192.168.1.11')
conn.login(account)
conn.execute('show ip route')
print conn.response
conn.send('exit\r')
conn.close()
上面的脚本会显示“show ip route”的结果。
但是如果我尝试执行conn.execute('show version'),脚本就会超时,因为Cisco设备期待用户按空格键继续、按回车键显示下一行,或者按任意键返回命令行。
我该如何执行show version命令,按两次空格键以显示整个输出,然后在Python中打印出来呢?
谢谢!!!!
3 个回答
2
我刚刚也问了同样的问题,下面的代码可以从一个列表中运行,并获取你想要的信息。
from __future__ import print_function
from netmiko import ConnectHandler
import sys
import time
import select
import paramiko
import re
fd = open(r'C:\NewdayTest.txt','w') # Where you want the file to save to.
old_stdout = sys.stdout
sys.stdout = fd
platform = 'cisco_ios'
username = 'username' # edit to reflect
password = 'password' # edit to reflect
ip_add_file = open(r'C:\IPAddressList.txt','r') # a simple list of IP addresses you want to connect to each one on a new line
for host in ip_add_file:
host = host.strip()
device = ConnectHandler(device_type=platform, ip=host, username=username, password=password)
output = device.send_command('terminal length 0')
output = device.send_command('enable') #Editable to be what ever is needed
print('##############################################################\n')
print('...................CISCO COMMAND SHOW RUN OUTPUT......................\n')
output = device.send_command('sh run')
print(output)
print('##############################################################\n')
print('...................CISCO COMMAND SHOW IP INT BR OUTPUT......................\n')
output = device.send_command('sh ip int br')
print(output)
print('##############################################################\n')
fd.close()
7
首先执行
terminal length 0
来关闭分页功能。
21
在运行 show version
之前,试着先执行 terminal length 0
。比如:
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
account = read_login()
conn = SSH2()
conn.connect('192.168.1.11')
conn.login(account)
conn.execute('terminal length 0')
conn.execute('show version')
print conn.response
conn.send('exit\r')
conn.close()
来自思科终端文档的说明:http://www.cisco.com/en/US/docs/ios/12_1/configfun/command/reference/frd1003.html#wp1019281