使用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()

相关文章

django 基于中间件实现限制ip频繁访问过程详解

额额,标题已经很醒目了,通过中间件去实现,其他方法也可以实现 浏览器前端传来的请求,必须通过中间件,才能到后面路由,视图函数,所以我们在中间件那里做一层处理,我们还需要知道是哪个ip,在...

简单了解python高阶函数map/reduce

简单了解python高阶函数map/reduce

高阶函数map/reduce Python内建了map()和reduce()函数。 我们先看map。map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数...

Python实现点阵字体读取与转换的方法

Python实现点阵字体读取与转换的方法

点阵字体是指根据文字的像素点来显示的字体,效果如下: 使用Python读取并显示的过程如下: 根据中文字符获取GB2312编码 通过GB2312编码计算该汉字在点阵字库中的区位和码位...

python 读取视频,处理后,实时计算帧数fps的方法

实时计算每秒的帧数 cap = cv2.VideoCapture("DJI_0008.MOV") #cap = cv2.VideoCapture(0) # Define the...

python绘制简单彩虹图

python绘制简单彩虹图

本文实例为大家分享了python绘制彩虹图的具体代码,供大家参考,具体内容如下 代码: from turtle import * #控制彩虹路径 def path(pen,...