设为首页 收藏本站
查看: 899|回复: 0

[经验分享] python snmp 自动化3-修改python的netsnmp库

[复制链接]

尚未签到

发表于 2015-12-15 08:42:42 | 显示全部楼层 |阅读模式
python snmp 自动化3-修改python的netsnmp库

#参考资料

           下面我们对client.py进行修改,去掉其中的函数部分,并为Session增加一些方法。以实现更加方便的访问:
           初始化时,增加3个字典:
          self.tid2OidDict =pickle.load(open(r"/usr/local/mib/tid2OidDict.txt"))
          self.tidAliasDict =pickle.load(open(r"/usr/local/mib/tidAliasDict.txt"))        
          self.tidTypeDict =pickle.load(open(r"/usr/local/mib/tidTypeDict.txt"))   
           增加列表转换方法:
    defconvert_args_to_list(self, args):
        """
        args is a list oftuple, for example:
        [
        ('ntpClientEnabled','0', 'false'),
        ('cmEthernetNetPortOamEnabled','1.1.1.1', 'false'),
       ('ecpaControlDuration', '1.1.1.1', '25')        
        ]
        """
        var_list = VarList()
        index = ''
        snmpValue = snmpType =None
        for  arg in args:
            tid = arg[0]
            snmpOid =self.get_oid_from_tid(tid)
            length = len(arg)

            if length >1:
                index = arg[1]

                #arg with tidindex value or more
                if len(arg)>2:
                    value =arg[2]
                    if tid in self.tidAliasDict:
                       snmpValue = self.convert_alias_to_value(tid,value)
                    else:
                       snmpValue =  value
                    snmpType =self.get_type_from_tid(tid)

                    iflen(arg) >3:
                       snmpType = arg[3]


            var =Varbind(snmpOid,index,snmpValue,snmpType)
           var_list.append(var)            
        return var_list
           增加把别名转换为实际值的方法:
    defconvert_alias_to_value(self, tid,value):
        if tid inself.tidAliasDict:
            snmpValue =self.tidAliasDict[tid][value]
        else:
            snmpValue = value      
        return snmpValue
     增加根据tid取得类型的方法:
    defget_type_from_tid(self, tid):
        returnself.tidTypeDict[tid]
     增加根据tid获取oid的方法:
    def get_oid_from_tid(self,tid):
        returnself.tid2OidDict[tid]
     其他函数也有少许修改。不一一列出:

这样,上次的创建和删除保护组就可以简化成:
import netsnmp
import ecpa

session =netsnmp.Session(Version=2,DestHost='172.23.192.44',Community='private')

resultList = session.set([
   ('cmFacProtGroupSwitchMode', '1.1.1.1','oneplusone'),
    ('cmFacProtGroupWorkPort','1.1.1.1',session.get_oid_from_tid('cmEthernetNetPortIndex') + '.1.1.1.1'),
    ('cmFacProtGroupProtPort','1.1.1.1',session.get_oid_from_tid('cmEthernetNetPortIndex') + '.1.1.1.2'),
   ('cmFacProtGroupRowStatus', '1.1.1.1','createAndGo')   
])

print resultList

resultList = session.set([
   ('cmFacProtGroupRowStatus', '1.1.1.1','destroy')   
])

print resultList

我们可以对具体的业务进行测试,定义如下的ecpa.py
"""
This file description ECPA operation in SNMP
"""
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Ssh to remote server
# Author:         Andrew Xu
# CreateDate: 2012/03/01
# $Id: $
# __version__ = $Revision: $

import netsnmp

class ecpaSnmp(object):
    def __init__(self,snmpObj):
        self.client = snmpObj
        
    def set_ecpa_stream(self,index, **args):
        keyDict = {
          'index':'ecpaConfigStreamIndex',
          'name':'ecpaConfigStreamName',
          'size':'ecpaConfigStreamFrameSize',
          'rate':'ecpaConfigStreamRate',
          'payloadType':'ecpaConfigStreamPayloadType',
          'destinationMAC':'ecpaConfigStreamDestinationMAC',
          'sourceMAC':'ecpaConfigStreamSourceMAC',
          'outerVlanEnabled':'ecpaConfigStreamOuterVlanEnabled',
          'outerVlanId':'ecpaConfigStreamOuterVlanId',
          'outerVlanPrio':'ecpaConfigStreamOuterVlanPrio',
         'outerVlanEtherType': 'ecpaConfigStreamOuterVlanEtherType',
          'innerVlanEnabled':'ecpaConfigStreamInnerVlanEnabled',
          'innerVlanId':'ecpaConfigStreamInnerVlanId',
          'innerVlanPrio':'ecpaConfigStreamInnerVlanPrio',
         'innerVlanEtherType': 'ecpaConfigStreamInnerVlanEtherType',
          'ipVersion':'ecpaConfigStreamIpVersion',
          'ipV4Address':'ecpaConfigStreamIpV4Address',
          'ipV6Address':'ecpaConfigStreamIpV6Address',
          'prioMapMode':'ecpaConfigStreamPrioMapMode',
          'prioVal':'ecpaConfigStreamPrioVal',
          'innerVlan2Enabled':'ecpaConfigStreamInnerVlan2Enabled',
          'innerVlan2Id':'ecpaConfigStreamInnerVlan2Id',
          'innerVlan2Prio':'ecpaConfigStreamInnerVlan2Prio',
         'innerVlan2EtherType': 'ecpaConfigStreamInnerVlan2EtherType',
          'destIpV4Address':'ecpaConfigStreamDestIpV4Address',
          'destIpV6Address':'ecpaConfigStreamDestIpV6Address',
          'usePortSourceMAC':'ecpaConfigStreamUsePortSourceMAC'
        }
      
      
        setList = []
        for arg in args:
            snmpName =keyDict[arg]
            snmpValue =args[arg]
            
            print snmpName,index, snmpValue
           setList.append((snmpName, index, snmpValue))
        returnself.client.set(setList)
  就可以通过如下方式调用刚才的库:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Ssh to remote server
# Author:         Andrew Xu
# CreateDate: 2012/02/28
import netsnmp
import ecpa

session =netsnmp.Session(Version=2,DestHost='172.23.192.44',Community='private')
#print session.tidAliasDict
ecpaExample = ecpa.ecpaSnmp(session)
resultList = ecpaExample.set_ecpa_stream(1,rate='96000',name='test',size='98')

print resultList     
现在还存在的问题有:walk只返回值,没有oid,这些问题留到下周解决。walk的示例如下:
resultList = session.walk([
   ('cmEthernetAccPortEntry'),
])
           返回的错误还没有捕捉。添加如下函数:
     def get_snmp_error(self):
         var_list = self.convert_args_to_list([('lastSetErrorInformation','0')])
         res = client_intf.get(self, var_list)
          return res
并对返回进行控制:
        if res != 1:
            return self.get_snmp_error()
        else:
            return res
现在执行出错时就会有错误报出:
# ./test.py
('Error: 257-  Entity already exists. (PROTGROUP-1-1-1-1)',)

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-151301-1-1.html 上篇帖子: Python中的for循环,codecademy 下篇帖子: python安装mysqldb
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表