• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python netsnmp.snmpwalk函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中netsnmp.snmpwalk函数的典型用法代码示例。如果您正苦于以下问题:Python snmpwalk函数的具体用法?Python snmpwalk怎么用?Python snmpwalk使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了snmpwalk函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: update

 def update(self):
     self.logger.info("Updating known mac addresses")
     switches = self.switch_collection.find()
     mac_count = 0
     for switch in switches:
         obj_switch = Switch(id = switch['_id'])
         oid = obj_switch.get('oid')
         ip = obj_switch.get('ip')
         read = obj_switch.get('read')
         switch_id = obj_switch.id
         mongo_doc = {}
         mongo_doc['switch_id'] = switch_id
         try:
             self.logger.debug("Requesting following data: oid=%s\tip=%s\tcommunity=%s\tswitch_id=%s" % (oid, ip, read, switch_id))
             varlist = netsnmp.VarList(netsnmp.Varbind(oid))
             res = netsnmp.snmpwalk(varlist, Version = 1,  DestHost = ip, Community = read)
             ifname_oid = '.1.3.6.1.2.1.31.1.1.1.1' # ifName
             self.logger.debug("Requesting following data: oid=%s\tip=%s\tcommunity=%s\tswitch_id=%s" % (ifname_oid, ip, read, switch_id))
             varlist_ifnames = netsnmp.VarList(netsnmp.Varbind(ifname_oid))
             res_ifnames = netsnmp.snmpwalk(varlist_ifnames, Version = 1,  DestHost = ip, Community = read)
             updated = datetime.datetime.utcnow()
             portnums = {}
             for i in range(len(varlist_ifnames)):
                 if bool(varlist_ifnames[i].iid):
                     pornnum = varlist_ifnames[i].iid
                 else:
                     pornnum = varlist_ifnames[i].tag.split('.')[-1:][0]
                 tmpvar = varlist_ifnames[i]
                 try:
                     portnums[int(pornnum)] = str(varlist_ifnames[i].val)
                 except:
                     pass
             for i in range(len(varlist)):
                 mac = ''
                 port = str(varlist[i].val)
                 try:
                     portname = portnums[int(varlist[i].val)]
                 except KeyError:
                     portname = port
                 for elem in varlist[i].tag.split('.')[-6:]:
                     mac += hex(int(elem)).split('x')[1].zfill(2) + ':'
                 mac = mac[:-1].lower()
                 mongo_doc['mac'] = mac
                 mongo_doc['port'] = port
                 mongo_doc['portname'] = portname
                 mongo_doc_updated = mongo_doc.copy()
                 mongo_doc_updated['updated'] = updated
                 res = self.known_mac_collection.find_and_modify(mongo_doc, {'$set': mongo_doc_updated}, upsert = True)
                 if not bool(res):
                     mac_count += 1
         except NameError:
             if self.logger:
                 self.logger.error("Cannot reach '{}'".format(ip))
         except:
             err = sys.exc_info()[0]
             if self.logger:
                 self.logger.error(err)
     if mac_count > 0:
         self.logger.info("Was added {} new mac addresses.".format(mac_count))
     return True
开发者ID:hicham-a,项目名称:luna,代码行数:60,代码来源:switch.py


示例2: equipment_monitor_interface_list

def equipment_monitor_interface_list(request, interface):
    interfaces = []
    id, sep , num = interface.partition("-")
    equipment = get_equipment(int(id))

    interfaces_name = netsnmp.snmpwalk(ifDescr,
                                           Version = 2,
                                           DestHost = equipment.ip,
                                           Community = "newtouch")

    interfaces_status = netsnmp.snmpwalk(ifOperStatus,
                                             Version = 2,
                                             DestHost = equipment.ip,
                                             Community = "newtouch")


    for name in interfaces_name:
        interface = EquipmentMonitorInterFace(interfaces_name.index(name),
                                              name,
                                              interfaces_status[interfaces_name.index(name)],
                                              equipment.ip)
        interface.fill_snmp_data()
        interface.fill_interface_ip()
        interfaces.append(interface)

    return interfaces
开发者ID:zouyapeng,项目名称:horizon-newtouch,代码行数:26,代码来源:monitor.py


示例3: check_neighbor_status_v4

def check_neighbor_status_v4(host,community):
    peers_v4   = {}
    asns_v4    = {}
    reasons_v4 = {}
  
    # Walk all peers from BGP-MIB
    oids_v4 = netsnmp.VarList( netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.3.1.4'))
    res_v4  = netsnmp.snmpwalk( oids_v4, Version = 2, DestHost = host, Community = community)
  
    # Due to SNMP deamon lagg in the router, when switching communities from one to the other,
    # sometimes we fail to get snmp.
    # If we wait 5 sec and try again it should work just fine
    if not res_v4:
        time.sleep(5)
        oids_v4 = netsnmp.VarList( netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.3.1.4'))
        res_v4  = netsnmp.snmpwalk( oids_v4, Version = 2, DestHost = host, Community = community)
        
    for oid_v4 in oids_v4:
        ipv4           = oid_v4.tag.replace("enterprises.9.9.187.1.2.5.1.3.1.4.", "")
        peers_v4[ipv4] = get_state(oid_v4.val)
    
        # Get RemoteAs from BGP-MIB
        asoid         = netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.11.1.4.'+ipv4)
        asn           = netsnmp.snmpget( asoid, Version = 2, DestHost = host, Community = community )
        asns_v4[ipv4] = asn[0]
    
        # Get lastErrorTxt from BGP-MIB
        reasonoid        = netsnmp.Varbind('.1.3.6.1.4.1.9.9.187.1.2.5.1.28.1.4.'+ipv4)
        reason           = netsnmp.snmpget( reasonoid, Version = 2, DestHost = host, Community = community )
        reasons_v4[ipv4] = reason[0]
        
    return (peers_v4,asns_v4,reasons_v4)
开发者ID:marcuseide,项目名称:iosxr-monitoring,代码行数:32,代码来源:check_bgp_neighbors.py


示例4: collect

    def collect(self):
        oid = netsnmp.VarList(netsnmp.Varbind(self.conf['poller_conf']['table']))
        netsnmp.snmpwalk(oid, DestHost=self.conf['hostname'], Version=self.conf['snmp_version'], Community=self.conf['snmp_community'], UseNumeric=True)

        tbl = {}
        for ret in oid:
            if ret.iid not in tbl:
                tbl[ret.iid] = {}

            tbl[ret.iid][ret.tag.split('.')[-1]] = ret.val
        tbl = sorted(tbl.items())

        for idx in xrange(len(tbl)):
            key, val = tbl[idx]
            for obj in self.conf['items']:
                skp = False
                for flt in obj.get('filter', ':'):
                    chk = flt.strip().split(':', 1)
                    skp = skp or not re.match(chk[1], val.get(chk[0], ''))

                if skp:
                    continue

                lbl = [val[i] if unicode(i).isnumeric() else i.format(index=idx, label=key) for i in obj['labels'].split('.')]
                self.data[self.escape(lbl)] = val[obj['values']]
开发者ID:mk23,项目名称:grapy,代码行数:25,代码来源:snmp_table.py


示例5: get_netgear_port_traffic

def get_netgear_port_traffic(hostname):
    """Returns [(port, octets_rcvd, octets_sent), ...]."""
    rcvd = netsnmp.snmpwalk('.1.3.6.1.2.1.2.2.1.10',
                            Version = 2,
                            Community = netgear_community,
                            DestHost = hostname)
    sent = netsnmp.snmpwalk('.1.3.6.1.2.1.2.2.1.16',
                            Version = 2,
                            Community = netgear_community,
                            DestHost = hostname)
    return zip(range(1,49), [map(int, k) for k in zip(rcvd, sent)])
开发者ID:mcreddy91,项目名称:network,代码行数:11,代码来源:wired.py


示例6: get_cisco_routing_table

def get_cisco_routing_table():
    """Returns [(mac_addr, ip_addr), ...]."""
    macs = netsnmp.snmpwalk('.1.3.6.1.2.1.3.1.1.2.51.1',
                            Version = 1,
                            Community = 'public',
                            DestHost = cisco_ip)
    ips = netsnmp.snmpwalk('.1.3.6.1.2.1.4.22.1.3.51',
                           Version = 1,
                           Community = 'public',
                           DestHost = cisco_ip)
    return zip(map(format_mac, macs), ips)
开发者ID:mcreddy91,项目名称:network,代码行数:11,代码来源:wired.py


示例7: get_netgear_mac_table

def get_netgear_mac_table(hostname):
    """Returns [(port, mac_addr), ...]."""
    macs = netsnmp.snmpwalk('.1.3.6.1.2.1.17.4.3.1.1',
                            Version = 2,
                            Community = netgear_community,
                            DestHost = hostname)
    ports = netsnmp.snmpwalk('.1.3.6.1.2.1.17.4.3.1.2',
                             Version = 2,
                             Community = netgear_community,
                             DestHost = hostname)
    return zip(map(int, ports), map(format_mac, macs))
开发者ID:mcreddy91,项目名称:network,代码行数:11,代码来源:wired.py


示例8: main

def main():
    
    streams = OrderedDict({})
    #streams = {}
    
    
    try:
        FILE = open(filename,'r')
        streams= pickle.load(FILE)
        print "Loaded File"
        print streams
    except:
        "No File, creating"


    print "Streams Read"
  
    hosts = ['192.168.11.200','192.168.11.1', '192.168.11.201']
    snmpTypes = ['ifInOctets','ifOutOctets','ifInUcastPkts','ifOutUcastPkts']

    for hostname in hosts:
        snmpHost = {'Community': 'public', 'DestHost': hostname, 'Version': 2}
        oid = netsnmp.VarList(netsnmp.Varbind('ifTable'))
        netsnmp.snmpwalk(oid,**snmpHost)
       
        ifNames = {} 
        for o in oid:
        
            if(o.tag == "ifDescr"):
                ifNames[o.iid] = o.val

            if(o.tag in snmpTypes):
                s =Stream(oid="%s.%s"%(o.tag,o.iid),
                        iid=o.iid,
                        tag=o.tag,
                        value=int(o.val),
                        host=hostname,
                        ifName=ifNames[o.iid])
                s.save(streams)

    #createStreams(streams)
    #print STREAMS
    results = processStreams(streams)
    print results
    postResults(results)
    try:
        FILE.close()
    except:
        pass

    f = open(filename,'w')
    pickle.dump(streams,f)
    f.close()
开发者ID:visgence,项目名称:portcullis,代码行数:53,代码来源:poller.py


示例9: get_net_equipment_snmpmsg

def get_net_equipment_snmpmsg(host, commit):
    snmpmsg = SnmpMessage()

    snmpmsg.cpu = netsnmp.snmpwalk(hh3cEntityExtCpuUsage,
                                         Version = 2,
                                         DestHost = host,
                                         Community = commit)

    snmpmsg.mem = netsnmp.snmpwalk(hh3cEntityExtMemUsage,
                                         Version = 2,
                                         DestHost = host,
                                         Community = commit)
    return snmpmsg
开发者ID:zouyapeng,项目名称:horizon-newtouch,代码行数:13,代码来源:monitor.py


示例10: fill_interface_ip

    def fill_interface_ip(self):
        ip_index = netsnmp.snmpwalk(ipAdEntIndex,
                                 Version = 2,
                                 DestHost = self.equipment_ip,
                                 Community = "newtouch")

        if str(self.id + 1) in ip_index:
            self.ip = netsnmp.snmpwalk(ipAdEntAddr,
                                 Version = 2,
                                 DestHost = self.equipment_ip,
                                 Community = "newtouch")[ip_index.index(str(self.id + 1))]
        else:
            self.ip = "-"
开发者ID:zouyapeng,项目名称:horizon-newtouch,代码行数:13,代码来源:monitor.py


示例11: snmp_walk

def snmp_walk(host, credential, *args, **kwargs):
    """Impelmentation of snmpwalk functionality

    :param host: switch ip
    :param credential: credential to access switch
    :param args: OIDs
    :param kwargs: key-value pairs
    """
    try:
        import netsnmp

    except ImportError:
        logging.error("Module 'netsnmp' do not exist! Please install it first")
        return None

    if 'version' not in credential or 'community' not in credential:
        logging.error("[utils] missing 'version' and 'community' in %s",
                      credential)
        return None

    version = None
    if credential['version'] in AUTH_VERSIONS:
        version = AUTH_VERSIONS[credential['version']]

    varbind_list = []
    for arg in args:
        varbind = netsnmp.Varbind(arg)
        varbind_list.append(varbind)

    var_list = netsnmp.VarList(*varbind_list)

    netsnmp.snmpwalk(var_list,
                     DestHost=host,
                     Version=version,
                     Community=credential['community'],
                     **kwargs)

    result = []
    if not var_list:
        logging.error("[hsdiscovery][utils][snmp_walk] retrived no record!")
        return result

    for var in var_list:
        response = {}
        response['elem_name'] = var.tag
        response['iid'] = var.iid
        response['value'] = var.val
        response['type'] = var.type
        result.append(response)

    return result
开发者ID:BruceZu,项目名称:compass-core,代码行数:51,代码来源:utils.py


示例12: snmp_walk

	def snmp_walk(self,iod):
		var=netsnmp.Varbind(iod)
		result = netsnmp.snmpwalk(var,
			Version = self.Version,
			DestHost = self.DestHost,
			Community = self.Community)
		return result
开发者ID:duxianghua,项目名称:python,代码行数:7,代码来源:snmp.py


示例13: check_pan_disk

def check_pan_disk(hostname, community):
    pan_disk_oid = '.1.3.6.1.2.1.25.2.3.1'
    oid = netsnmp.Varbind(pan_disk_oid)
    #logger.debug('oid %s',oid)
    output = netsnmp.snmpwalk(oid, Version=2, DestHost=hostname, Community=community)
    #logger.debug('output %s',output)
   # return output 

#def calc_pan_disk():
    [index, oid, descr, allocUt, AvailS, UsedS] = [output[i:i+11] for i in range(0,len(output),11)]
    disk_info= descr[0:5]+AvailS[0:5]+UsedS[0:5]
    [Disktype, AvailSize, UsedSize] =[disk_info[i:i+5] for i in range(0,len(disk_info),5)]

#List for all types of Disk on the pans
    ram = Disktype[0],AvailSize[0],UsedSize[0]
    sd = Disktype[1],AvailSize[1],UsedSize[1]
    cfg_dk = Disktype[2],AvailSize[2],UsedSize[2]
    lg_dk = Disktype[3],AvailSize[3],UsedSize[3]
    rt_dk = Disktype[4],AvailSize[4],UsedSize[4]
    
    #print ram
    #print sd
    #print cfg_dk
    #print lg_dk
    #print rt_dk

#Zipping all lists together
    disks= zip(ram, sd, cfg_dk, lg_dk, rt_dk)
   #print disks

#flatten the list
    dk_flat  = [val for sublist in disks for val in sublist]
    #print dk_flat

#Slicing lists to create key value pairs for dictionary
    disk_keys = dk_flat[0:5]
    disk_av_values = dk_flat[5:10]
    disk_used_values = dk_flat[10:15]
    #print disk_keys
    #print disk_av_values
    #print disk_used_values

#Creating a dictionary 
    d = dict(zip(disk_keys,zip(disk_av_values,disk_used_values)))
    pprint (d)

# percentange calculation
    for key in d:
    #d2 = {key: (v1,v2,((int(v2)/int(v1))*100)) for key,(v1,v2) in d.items()}
    #print d2
        perc_usage = float( float(d[key][1])/float(d[key][0]))*100
        # print key, usage
        if perc_usage > 30.0:
         alert_level = 'CRITICAL'
         print "Disk name" + " " + key + " " + "is using more than 30%"
        elif perc_usage > 10.0:
         alert_level = 'WARNING'
         print "Disk name" + " " + key + " " + "is using more than 10%"
        else:
         alert_level = 'OK' 
开发者ID:srdpython,项目名称:projects,代码行数:60,代码来源:pan_disk_check.py


示例14: ifindex_re

def ifindex_re():
    oid_jnxOperatingState_RE = ".1.3.6.1.4.1.2636.3.1.13.1.6.9"
    result_ifindex_re = netsnmp.snmpwalk(netsnmp.Varbind(oid_jnxOperatingState_RE), **args)
    if len(result_ifindex_re) > 1:
        return result_ifindex_re
    else:
        return tuple(result_ifindex_re[0])
开发者ID:kevinnguyeneng,项目名称:ProjectAUtOS,代码行数:7,代码来源:tuanna_check_port_juniper.py


示例15: query

 def query(self):
     """Creates SNMP query session"""
     try:
         result = netsnmp.snmpwalk(self.oid, Version=self.version, DestHost=self.destHost, Community=self.community)
     except Exception, err:
         print err
         result = None
开发者ID:lail3344,项目名称:py4sa,代码行数:7,代码来源:snmp.py


示例16: getServiceTag

def getServiceTag(hst,com):
    	oid = netsnmp.VarList(netsnmp.Varbind('.1.3.6.1.4.1.674.10892.1.300.10.1.11'))
    	res = netsnmp.snmpwalk(oid, Version = 2, DestHost=hst, Community=com)
	if str(res) != "()":
                return res
        else:
                print "Couldn't read snmp value"
                sys.exit(3)
开发者ID:jpajicek,项目名称:nagios,代码行数:8,代码来源:check_dell_warranty.py


示例17: getOIDsButton_clicked

 def getOIDsButton_clicked(self):
     if(self.lineEditIP.text() <> ""):
         ip = str(self.lineEditOID.text())
         vars =  netsnmp.VarList( netsnmp.Varbind('ifDescr'))
         res  = netsnmp.snmpwalk( vars, Version = 1, DestHost = ip, Community = 'public' )
         print res
     else:
         print "IP Required!"
开发者ID:jlgutierrez,项目名称:wr-desktop-manager,代码行数:8,代码来源:Qt_getOIDs_app.py


示例18: walk

    def walk(self, oid):
        """ Ejecuta el equivalente a un 'snmpwalk' con los parametros establecidos """

        try:
            result = netsnmp.snmpwalk(oid, Version=self.version, DestHost=self.desthost,
                                      SecName=self.username, Community=self.community, Timeout=self.timeout)
            return result
        except Exception as e:
            print type(e)
开发者ID:asamarin,项目名称:power-aware,代码行数:9,代码来源:snmp.py


示例19: walk_data

def walk_data(host, version, community, oid):
    var = netsnmp.Varbind(oid)
    try:
        data = netsnmp.snmpwalk(var, Version=version, DestHost=host, Community=community)
    except:
        helper.exit(summary="\n SNMP connection to device failed " + oid, exit_code=unknown, perfdata='')
    if not data:
        helper.exit(summary="\n SNMP connection to device failed " + oid, exit_code=unknown, perfdata='')
    return data
开发者ID:rsmm01,项目名称:check_snmp_raritan,代码行数:9,代码来源:check_snmp_raritan.py


示例20: SNMPSERVER

def SNMPSERVER(ID,IP,Community,port): #Apache server snmp monitoring here
 oid=netsnmp.Varbind('.1.3.6.1.4.1.8072.1.3.1.4.1.2.6.97.112.97.99.104.101')
 IP=IP+":"+str(port)
 val=netsnmp.snmpwalk(oid, Version = 1, DestHost="%s" %IP, Community="%s" %Community )
 if len(val)==4:
  l=os.system('rrdtool update {0}.rrd N:{1}:{2}:{3}:{4} '.format(ID,val[0],val[1],val[2],val[3]))
  if l!=0:#rrd condition
   os.system('rrdtool create  {0}.rrd --step 60  DS:CPUusage:GAUGE:120:U:U DS:reqpersec:GAUGE:120:U:U DS:bytespersec:GAUGE:120:U:U DS:bytesperreq:GAUGE:120:U:U RRA:AVERAGE:0.5:1:1440 '.format(ID))
   os.system('rrdtool update {0}.rrd N:{1}:{2}:{3}:{4} '.format(ID,val[0],val[1],val[2],val[3]))
  print ID,IP,val[0],val[1],val[2],val[3]
开发者ID:Sathvik777,项目名称:TCP-ip-,代码行数:10,代码来源:backend.py



注:本文中的netsnmp.snmpwalk函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python netutils.isValidIp函数代码示例发布时间:2022-05-27
下一篇:
Python netsnmp.snmpget函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap