使用Python脚本来获取Cisco设备信息的示例

yipeiwu_com6年前Python基础

今天发现一个使用python写的管理cisco设备的小框架tratto,可以用来批量执行命令。

下载后主要有3个文件:

Systems.py 定义了一些不同设备的操作系统及其常见命令。

Connectivity.py 是主要实现功能的代码,其实主要就是使用了python的pexpect模块。

Driver.py是一个示例文件。

[root@safe tratto-master]# cat driver.py
#!/usr/bin/env python
import Connectivity
import Systems
#telnet to a cisco switch
m = Systems.OperatingSystems['IOS']
s = Connectivity.Session("192.168.1.1",23,"telnet",m)
s.login("yourusername", "yourpassword")
# if your need to issue an "enable" command
s.escalateprivileges('yourenablepassword')
s.sendcommand("show clock")
s.sendcommand("show run")
s.logout()

以上就是示例driver.py的内容,使用很简单。

首先选择一个设备系统版本,此例cisco交换机,所以使用了IOS。作者现在写的可以支持的设备系统有:

OperatingSystems = {

  'IOS': CiscoIOS,

  'WebNS': CiscoWebNS,

  'OSX': AppleOSX,

  'SOS': SecureComputingSidewinder,

  'AOS': ArubaOS,

  'OBSD': OpenBSD,

  }

然后填写ip,端口,telnet或者ssh,最后就是上步选择的系统版本。login填上登陆凭证。

s.escalateprivileges是特权凭证。so easy~

以下是我写的一个使用脚本,抓取交换机的一些信息,然后保存到文件。

[root@safe tratto-master]# cat cisco.py
#!/usr/bin/env python
#
# Cisco Switch commands
# By s7eph4ni3
#
import Connectivity
import Systems
m = Systems.OperatingSystems['IOS']
iplist = ['192.168.1.1','192.168.1.2']
cmdlist = ['show ip int brief','show cdp nei detail','show arp','show ver']
for ip in iplist:
  if ip == '192.168.1.1':
    s = Connectivity.Session(ip,23,"telnet",m)
    s.login("", "passwd")
  else:
    s = Connectivity.Session(ip,22,"ssh",m)
    s.login("username", "passwd")
  s.escalateprivileges('enpasswd')
  f = open(ip+'.txt','w+')
  for cmd in cmdlist:
    a = s.sendcommand(cmd)
    f.write(ip+cmd+'\n')
    f.write(a+'\n')
  f.close()
  s.logout()

相关文章

python生成随机红包的实例写法

假设红包金额为money,数量是num,并且红包金额money>=num*0.01 原理如下,从1~money*100的数的集合中,随机抽取num-1个数,然后对这些数进行排序,在...

Python 获取命令行参数内容及参数个数的实例

执行python脚本的时候,有时需要获取命令行参数的相关信息。C语言通过argc和argv来获取参数的个数和参数的内容,python中通过sys模块的argv来获取参数的内容,使用len...

Python库urllib与urllib2主要区别分析

作为一个Python菜鸟,之前一直懵懂于urllib和urllib2,以为2是1的升级版。今天看到老外写的一篇《Python: difference between urllib and...

用Python输出一个杨辉三角的例子

关于杨辉三角是什么东西,右转维基百科:杨辉三角 稍微看一下直观一点的图:复制代码 代码如下:        1       1 1      1 2 1     1 3 3 1    1...

Python装饰器decorator用法实例

本文实例讲述了Python装饰器decorator用法。分享给大家供大家参考。具体分析如下: 1. 闭包(closure) 闭包是Python所支持的一种特性,它让在非global sc...