使用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实现在tkinter中使用matplotlib绘制图形的方法示例

Python实现在tkinter中使用matplotlib绘制图形的方法示例

本文实例讲述了Python实现在tkinter中使用matplotlib绘制图形的方法。分享给大家供大家参考,具体如下: 一. 代码: # coding=utf-8 import s...

详解Python3中yield生成器的用法

任何使用yield的函数都称之为生成器,如: def count(n): while n > 0: yield n #生成值:n n -= 1...

用Python将IP地址在整型和字符串之间轻松转换

前言 大家应该都有所体会,对于字符串型的IP存入数据库中,实在是个即浪费空间又浪费性能的家伙,所以可爱的人们想出来将IP转换为整型存储。MySQL中存在INET_ATON() 、INET...

Python字符串处理之count()方法的使用

 count()方法返回出现在范围内串子数range [start, end]。可选参数的start和end都解释为片符号。 语法 以下是count()方法的语法: str...

Python连接phoenix的方法示例

本文实例讲述了Python连接phoenix的方法。分享给大家供大家参考,具体如下: phoenix是由saleforce.com开源的一个项目,后又捐给了Apache。它相当于一个Ja...