[英]Using Python to Telnet into CISCO router and store the output on a machine locally
我是python的新手,我设法使用python代码远程登录到cisco路由器。 我可以在屏幕上显示命令,但是我想将输出本地保存在我的linux机器上,也就是python脚本所在的位置。
有什么建议么?
我的目标是将输出存储在本地,然后导入matplotlib绘制一些漂亮的带宽使用情况,CPU使用情况,内存使用情况以及接口使用情况图表。
对于您要执行的操作,应该考虑使用SNMP,而不是尝试处理telnet I / O。
您将能够提取所描述的值,并将其放入您选择的数据存储中(文本,mysql等)。
http://pysnmp.sourceforge.net/
http://www.cisco.com/zh-CN/docs/ios/12_2/configfun/configuration/guide/fcf014.html
下面的脚本会将您的数据保存到运行此脚本的服务器上的文件中。 文件名将为routeroutput。 只需在下面的代码中输入交换机IP,密码并启用密码,然后使用python在服务器上运行即可。
它需要一个名为pexpect的附加模块。 您可以从这里https://pypi.python.org/pypi/pexpect/下载并安装它。
import pexpect
try:
switchIP= 'x.x.x.x'
switchPassword = 'your-switch-password'
switchEnable= 'your-enable-password'
commandTorun= 'The command you want to run'
telnet = 'telnet ' + switchIP
#Login to the switch
t=pexpect.spawn(telnet)
t.expect('word:')
t.sendline(switchPassword)
t.expect('#')
t.sendline(switchEnable)
t.expect('>')
#Send the command
t.sendline('commandTorun')
t.expect('>')
data = t.before
#Closing the Telnet Connection
t.sendline('exit')
t.expect('>')
t.sendline('exit')
t.expect(pexpect.EOF)
#Opening the file and writing the data to it
f = open('routeroutput', 'w')
f.write(data)
f.close()
except Exception, e:
print "The Script failed to login"
print str(e)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.