使用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实现删除列表中某个元素的3种方法

python中关于删除list中的某个元素,一般有三种方法:remove、pop、del: 1.remove: 删除单个元素,删除首个符合条件的元素,按值删除 举例说明: >...

python tkinter基本属性详解

python tkinter基本属性详解

1.外形尺寸 尺寸单位:只用默认的像素或者其他字符类的值!,不要用英寸毫米之类的内容。 btn = tkinter.Button(root,text = '按钮') # 设置按钮尺寸...

python开发之str.format()用法实例分析

本文实例分析了python开发之str.format()用法。分享给大家供大家参考,具体如下: 格式化一个字符串的输出结果,我们在很多地方都可以看到,如:c/c++中都有见过 下面看看p...

解决python报错MemoryError的问题

如下: python 32bit 最大只能使用 2G 内存,坑爹之处,超过 2G 报错MemoryError。 而 64bit python则无此限制,所以建议使用 64bit pyth...

python实现在无须过多援引的情况下创建字典的方法

本文实例讲述了python实现在无须过多援引的情况下创建字典的方法。分享给大家供大家参考。具体实现方法如下: 1.使用itertools模块 import itertools the...