def main(): module = AnsibleModule( argument_spec=dict( host=dict(type='str', required=True), version=dict(type='str', required=True, choices=['v2', 'v2c', 'v3']), community=dict(type='str'), username=dict(type='str'), level=dict(type='str', choices=['authNoPriv', 'authPriv']), integrity=dict(type='str', choices=['md5', 'sha']), privacy=dict(type='str', choices=['aes', 'des']), authkey=dict(type='str'), privkey=dict(type='str'), ), required_together=( ['username', 'level', 'integrity', 'authkey'], ['privacy', 'privkey'], ), supports_check_mode=False, ) m_args = module.params if not has_pysnmp: module.fail_json(msg=missing_required_lib('pysnmp'), exception=PYSNMP_IMP_ERR) cmdGen = cmdgen.CommandGenerator() # Verify that we receive a community when using snmp v2 if m_args['version'] == "v2" or m_args['version'] == "v2c": if m_args['community'] is None: module.fail_json(msg='Community not set when using snmp version 2') if m_args['version'] == "v3": if m_args['username'] is None: module.fail_json(msg='Username not set when using snmp version 3') if m_args['level'] == "authPriv" and m_args['privacy'] is None: module.fail_json( msg='Privacy algorithm not set when using authPriv') if m_args['integrity'] == "sha": integrity_proto = cmdgen.usmHMACSHAAuthProtocol elif m_args['integrity'] == "md5": integrity_proto = cmdgen.usmHMACMD5AuthProtocol if m_args['privacy'] == "aes": privacy_proto = cmdgen.usmAesCfb128Protocol elif m_args['privacy'] == "des": privacy_proto = cmdgen.usmDESPrivProtocol # Use SNMP Version 2 if m_args['version'] == "v2" or m_args['version'] == "v2c": snmp_auth = cmdgen.CommunityData(m_args['community']) # Use SNMP Version 3 with authNoPriv elif m_args['level'] == "authNoPriv": snmp_auth = cmdgen.UsmUserData(m_args['username'], authKey=m_args['authkey'], authProtocol=integrity_proto) # Use SNMP Version 3 with authPriv else: snmp_auth = cmdgen.UsmUserData(m_args['username'], authKey=m_args['authkey'], privKey=m_args['privkey'], authProtocol=integrity_proto, privProtocol=privacy_proto) # Use p to prefix OIDs with a dot for polling p = DefineOid(dotprefix=True) # Use v without a prefix to use with return values v = DefineOid(dotprefix=False) def Tree(): return defaultdict(Tree) results = Tree() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.sysDescr, ), cmdgen.MibVariable(p.sysObjectId, ), cmdgen.MibVariable(p.sysUpTime, ), cmdgen.MibVariable(p.sysContact, ), cmdgen.MibVariable(p.sysName, ), cmdgen.MibVariable(p.sysLocation, ), lookupMib=False) if errorIndication: module.fail_json(msg=str(errorIndication)) for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if current_oid == v.sysDescr: results['ansible_sysdescr'] = decode_hex(current_val) elif current_oid == v.sysObjectId: results['ansible_sysobjectid'] = current_val elif current_oid == v.sysUpTime: results['ansible_sysuptime'] = current_val elif current_oid == v.sysContact: results['ansible_syscontact'] = current_val elif current_oid == v.sysName: results['ansible_sysname'] = current_val elif current_oid == v.sysLocation: results['ansible_syslocation'] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.ifIndex, ), cmdgen.MibVariable(p.ifDescr, ), cmdgen.MibVariable(p.ifMtu, ), cmdgen.MibVariable(p.ifSpeed, ), cmdgen.MibVariable(p.ifPhysAddress, ), cmdgen.MibVariable(p.ifAdminStatus, ), cmdgen.MibVariable(p.ifOperStatus, ), cmdgen.MibVariable(p.ipAdEntAddr, ), cmdgen.MibVariable(p.ipAdEntIfIndex, ), cmdgen.MibVariable(p.ipAdEntNetMask, ), cmdgen.MibVariable(p.ifAlias, ), lookupMib=False) if errorIndication: module.fail_json(msg=str(errorIndication)) interface_indexes = [] all_ipv4_addresses = [] ipv4_networks = Tree() for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.ifIndex in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['ansible_interfaces'][ifIndex]['ifindex'] = current_val interface_indexes.append(ifIndex) if v.ifDescr in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['ansible_interfaces'][ifIndex]['name'] = current_val if v.ifMtu in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['ansible_interfaces'][ifIndex]['mtu'] = current_val if v.ifSpeed in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['ansible_interfaces'][ifIndex]['speed'] = current_val if v.ifPhysAddress in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['ansible_interfaces'][ifIndex]['mac'] = decode_mac( current_val) if v.ifAdminStatus in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['ansible_interfaces'][ifIndex][ 'adminstatus'] = lookup_adminstatus(int(current_val)) if v.ifOperStatus in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['ansible_interfaces'][ifIndex][ 'operstatus'] = lookup_operstatus(int(current_val)) if v.ipAdEntAddr in current_oid: curIPList = current_oid.rsplit('.', 4)[-4:] curIP = ".".join(curIPList) ipv4_networks[curIP]['address'] = current_val all_ipv4_addresses.append(current_val) if v.ipAdEntIfIndex in current_oid: curIPList = current_oid.rsplit('.', 4)[-4:] curIP = ".".join(curIPList) ipv4_networks[curIP]['interface'] = current_val if v.ipAdEntNetMask in current_oid: curIPList = current_oid.rsplit('.', 4)[-4:] curIP = ".".join(curIPList) ipv4_networks[curIP]['netmask'] = current_val if v.ifAlias in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['ansible_interfaces'][ifIndex][ 'description'] = current_val interface_to_ipv4 = {} for ipv4_network in ipv4_networks: current_interface = ipv4_networks[ipv4_network]['interface'] current_network = { 'address': ipv4_networks[ipv4_network]['address'], 'netmask': ipv4_networks[ipv4_network]['netmask'] } if current_interface not in interface_to_ipv4: interface_to_ipv4[current_interface] = [] interface_to_ipv4[current_interface].append(current_network) else: interface_to_ipv4[current_interface].append(current_network) for interface in interface_to_ipv4: results['ansible_interfaces'][int( interface)]['ipv4'] = interface_to_ipv4[interface] results['ansible_all_ipv4_addresses'] = all_ipv4_addresses module.exit_json(ansible_facts=results)
def snmp_get_oid_v3(snmp_device, snmp_user, oid='.1.3.6.1.2.1.1.1.0', auth_proto='sha', encrypt_proto='aes128', display_errors=True): ''' Retrieve the given OID Default OID is MIB2, sysDescr snmp_device is a tuple = (name_or_IP, snmp_port) snmp_user is a tuple = (user_name, auth_key, encrypt_key) Defaults to SHA1-AES128 for authentication + encryption auth_proto can be 'sha' or 'md5' or 'none' encrypt_proto can be 'aes128', 'aes192', 'aes256', '3des', 'des', or 'none' From PySNMP manuals: http://pysnmp.sourceforge.net/docs/current/security-configuration.html Optional authProtocol parameter may be used to specify non-default hash function algorithm. Possible values include: usmHMACMD5AuthProtocol -- MD5-based authentication protocol usmHMACSHAAuthProtocol -- SHA-based authentication protocol usmNoAuthProtocol -- no authentication to use (default) Optional privProtocol parameter may be used to specify non-default ciphering algorithm. Possible values include: usmDESPrivProtocol -- DES-based encryption protocol usmAesCfb128Protocol -- AES128-based encryption protocol (RFC3826) usm3DESEDEPrivProtocol -- triple DES-based encryption protocol (Extended Security Options) usmAesCfb192Protocol -- AES192-based encryption protocol (Extended Security Options) usmAesCfb256Protocol -- AES256-based encryption protocol (Extended Security Options) usmNoPrivProtocol -- no encryption to use (default) ''' # unpack snmp_user a_user, auth_key, encrypt_key = snmp_user auth_proto_map = { 'sha': cmdgen.usmHMACSHAAuthProtocol, 'md5': cmdgen.usmHMACMD5AuthProtocol, 'none': cmdgen.usmNoAuthProtocol } if auth_proto in auth_proto_map.keys(): auth_protocol = auth_proto_map[auth_proto] else: raise ValueError("Invalid authentication protocol specified: %s" % auth_proto) encrypt_proto_map = { 'des': cmdgen.usmDESPrivProtocol, '3des': cmdgen.usm3DESEDEPrivProtocol, 'aes128': cmdgen.usmAesCfb128Protocol, 'aes192': cmdgen.usmAesCfb192Protocol, 'aes256': cmdgen.usmAesCfb256Protocol, 'none': cmdgen.usmNoPrivProtocol, } if encrypt_proto in encrypt_proto_map.keys(): encrypt_protocol = encrypt_proto_map[encrypt_proto] else: raise ValueError("Invalid encryption protocol specified: %s" % encrypt_proto) # Create a PYSNMP cmdgen object cmd_gen = cmdgen.CommandGenerator() (error_detected, error_status, error_index, snmp_data) = cmd_gen.getCmd(cmdgen.UsmUserData( a_user, auth_key, encrypt_key, authProtocol=auth_protocol, privProtocol=encrypt_protocol, ), cmdgen.UdpTransportTarget(snmp_device), oid, lookupNames=True, lookupValues=True) if not error_detected: return snmp_data else: if display_errors: print('ERROR DETECTED: ') print(' %-16s %-60s' % ('error_message', error_detected)) print(' %-16s %-60s' % ('error_status', error_status)) print(' %-16s %-60s' % ('error_index', error_index)) return None
from pysnmp.entity.rfc3413.oneliner import cmdgen SNMP_HOST = 'localhost' SNMP_PORT = 161 SNMP_COMMUNITY = 'public' if __name__ == '__main__': cmd_generator = cmdgen.CommandGenerator() error_notify, error_status, error_index, var_binds = cmd_generator.getCmd( cmdgen.CommunityData(SNMP_COMMUNITY), cmdgen.UdpTransportTarget((SNMP_HOST, SNMP_PORT)), cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr', 0), lookupNames=True, lookValues=True ) #Check for errors and print out results if error_notify: print(error_notify) elif error_status: print(error_status) else: for name, val in var_binds: print('%s = %s' %(name.prettyPrint(), val.prettyPrint()))
#!/usr/bin/python3.5 # -- URL para teste "demo.snmplabs.com" from pysnmp.entity.rfc3413.oneliner import cmdgen cmdGen = cmdgen.CommandGenerator() comunidades = ["admin", "cisco", "public", "private"] ipAdd = input("Digite o endereço IP do alvo: ") for i in comunidades: snmpCmdGen = cmdgen.CommandGenerator() snmpTransportData = cmdgen.UdpTransportTarget((ipAdd, 161), timeout=1.5, retries=0) # mib = cmdgen.MibVariable('SNMPv2-MIB', 'sysDescr' , 0) error, errorStatus, errorIndex, binds = snmpCmdGen.getCmd( cmdgen.CommunityData(i), snmpTransportData, "1.3.6.1.2.1.1.5.0", "1.3.6.1.2.1.1.1.0", "1.3.6.1.2.1.1.3.0") if error: print(str(error) + " # -- Comunidade %s não encontrada." % (i)) else: print("Comunidade '%s' ... encontrada." % (i)) for bind in binds: print(' = '.join([x.prettyPrint() for x in bind]))
def getPortFromSnmpVersion2C(self, mininetOption, initConnection): # init value count = 0 cmdGen = None tempHwAddr = "" # list port dictPort = {} try: # create object for create snmp command cmdGen = cmdgen.CommandGenerator() except Exception as err: print(" 94 Switch ip " + self.switchIp + " terminate because handling run-time error : " + str(err)) sys.exit() while count < self.numberOfRetransmission: try: # connect to snmp at switch errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget((self.switchIp, 161)), '1.0.8802.1.1.2.1.3.7.1.3', '1.0.8802.1.1.2.1.3.7.1.4') if errorIndication: print(errorIndication) count += 1 if count == 1: #send del port to controller for snmpPosition, port in self.dictActivePort.items(): packed_data = portStatus( reason=portReason.OFPPR_DELETE, desc=port) packed_data = packed_data.pack() self.s.send(packed_data) # del port from dict all active port in TDA if len(self.dictActivePort.items()) > 0: try: self.lock.acquire_write() for snmpPosition, port in self.dictActivePort.items( ): del self.dictAllActivePortInTDA[( port.hw_addr, port.name)] self.lock.release() except: self.lock.release() del self.dictActivePort self.dictActivePort = {} else: if errorStatus: print( '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?')) count += 1 if count == 1: #send del port to controller for snmpPosition, port in self.dictActivePort.items( ): packed_data = portStatus( reason=portReason.OFPPR_DELETE, desc=port) packed_data = packed_data.pack() self.s.send(packed_data) # del port from dict all active port in TDA if len(self.dictActivePort.items()) > 0: try: self.lock.acquire_write() for snmpPosition, port in self.dictActivePort.items( ): del self.dictAllActivePortInTDA[( port.hw_addr, port.name)] self.lock.release() except: self.lock.release() del self.dictActivePort self.dictActivePort = {} else: # init value #index = 1 # number of port if self.mininetOption == 1 and len(varBindTable) > 0: del varBindTable[len(varBindTable) - 1] for i in varBindTable: # mac address tempHwAddr = i[0][1].prettyPrint() tempHwAddr = tempHwAddr[2:len(tempHwAddr)] if (len(tempHwAddr) != 12): print( "Error invalid mac address from local port in snmp" ) else: tempHwAddr = tempHwAddr[0:2] + ":" + tempHwAddr[ 2:4] + ":" + tempHwAddr[ 4:6] + ":" + tempHwAddr[ 6:8] + ":" + tempHwAddr[ 8:10] + ":" + tempHwAddr[10:12] tempPPort = PPort(i[0][0][-1], tempHwAddr, i[1][1].prettyPrint(), 0, 0, 192, 0, 0, 0) dictPort[str( i[0][0][-1] )] = tempPPort # type interger chage to str """ print("key : " + str(i[0][0][-1]) ) print("item : " + tempPPort ) """ """ key : poistion of active port in snmp (2) item : PPort(object) """ #index += 1 return dictPort, tempHwAddr except Exception as err: count += 1 if count == 1: #send del port to controller for snmpPosition, port in self.dictActivePort.items(): packed_data = portStatus( reason=portReason.OFPPR_DELETE, desc=port) packed_data = packed_data.pack() self.s.send(packed_data) # del port from dict all active port in TDA if len(self.dictActivePort.items()) > 0: try: self.lock.acquire_write() for snmpPosition, port in self.dictActivePort.items( ): del self.dictAllActivePortInTDA[(port.hw_addr, port.name)] self.lock.release() except: self.lock.release() del self.dictActivePort self.dictActivePort = {} print(" 165 Switch ip " + self.switchIp + " handling run-time error : " + str(err)) print(" Switch ip " + self.switchIp + " terminate because : it has problem about snmp ") if initConnection: sys.exit() else: return dictPort, None
else: # Maybe a hostname was entered... try: ip = socket.gethostbyname(host) except Exception, e: mesg = "ERROR: Host (" + host + ") not registered in DNS " + str(e) + "\n" sys.stderr.write(mesg) mesg = "Unable to resolve hostname" + "\n" sys.stderr.write(mesg) exit() a={} oid = eval(str("1,3,6,1,2,1,1,1,0")) __errorIndication, __errorStatus, __errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( \ cmdgen.CommunityData('my-agent', user, 0), \ cmdgen.UdpTransportTarget((host, 161)), oid) if len(varBinds) < 1: mesg = "Incorrect authentication details" self.log.error(mesg) return -1 a['hw_make'] = str(varBinds[0][1]) oid = eval("1,3,6,1,4,1,13742,4,1,1,6,0") __errorIndication, __errorStatus, __errorIndex, varBinds = cmdgen.CommandGenerator().getCmd( \ cmdgen.CommunityData('my-agent', user, 0), \ cmdgen.UdpTransportTarget((host, 161)), oid) x = [] for d in ['%x' % ord(i) for i in varBinds[0][1]]:
def __init__(self): super(SNMPInspector, self).__init__() self._cmdGen = cmdgen.CommandGenerator()
def snmp_walk(host, version, community): cmdGen = cmdgen.CommandGenerator() # Use SNMP Version 2 # if version == "v2" or version == "v2c": snmp_auth = cmdgen.CommunityData(community) # Use p to prefix OIDs with a dot for polling p = DefineOid(dotprefix=True) # Use v without a prefix to use with return values v = DefineOid(dotprefix=False) def Tree(): return defaultdict(Tree) results = Tree() results['error'] = False errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( snmp_auth, cmdgen.UdpTransportTarget((host, 161)), cmdgen.MibVariable(p.sysDescr, ), cmdgen.MibVariable(p.sysObjectId, ), cmdgen.MibVariable(p.sysUpTime, ), cmdgen.MibVariable(p.sysContact, ), cmdgen.MibVariable(p.sysName, ), cmdgen.MibVariable(p.sysLocation, ), lookupMib=False) if errorIndication: results['error'] = True results['error_msg'] = str(errorIndication) for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if current_oid == v.sysDescr: results['ansible_sysdescr'] = decode_hex(current_val) elif current_oid == v.sysObjectId: results['ansible_sysobjectid'] = current_val elif current_oid == v.sysUpTime: results['ansible_sysuptime'] = current_val elif current_oid == v.sysContact: results['ansible_syscontact'] = current_val elif current_oid == v.sysName: results['ansible_sysname'] = current_val elif current_oid == v.sysLocation: results['ansible_syslocation'] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((host, 161)), cmdgen.MibVariable(p.ifIndex, ), cmdgen.MibVariable(p.ifDescr, ), cmdgen.MibVariable(p.ifMtu, ), cmdgen.MibVariable(p.ifSpeed, ), cmdgen.MibVariable(p.ifPhysAddress, ), cmdgen.MibVariable(p.ifAdminStatus, ), cmdgen.MibVariable(p.ifOperStatus, ), cmdgen.MibVariable(p.ipAdEntAddr, ), cmdgen.MibVariable(p.ipAdEntIfIndex, ), cmdgen.MibVariable(p.ipAdEntNetMask, ), cmdgen.MibVariable(p.ifAlias, ), lookupMib=False) if errorIndication: results['error'] = True results['error_msg'] = str(errorIndication) return results
def __init__(self, Community, DestHost, MIB, Version=1): self.version = Version self.mid = MIB self.destHost = DestHost self.community = Community self.cg = cmdgen.CommandGenerator()
def main(): module = AnsibleModule(argument_spec=dict( host=dict(required=True), timeout=dict(reqired=False, type='int', default=5), version=dict(required=True, choices=['v2', 'v2c', 'v3']), community=dict(required=False, default=False), username=dict(required=False), level=dict(required=False, choices=['authNoPriv', 'authPriv']), integrity=dict(required=False, choices=['md5', 'sha']), privacy=dict(required=False, choices=['des', 'aes']), authkey=dict(required=False), privkey=dict(required=False), is_dell=dict(required=False, default=False, type='bool'), is_eos=dict(required=False, default=False, type='bool'), removeplaceholder=dict(required=False)), required_together=( ['username', 'level', 'integrity', 'authkey'], ['privacy', 'privkey'], ), supports_check_mode=False) m_args = module.params if not has_pysnmp: module.fail_json(msg='Missing required pysnmp module (check docs)') cmdGen = cmdgen.CommandGenerator() # Verify that we receive a community when using snmp v2 if m_args['version'] == "v2" or m_args['version'] == "v2c": if m_args['community'] == False: module.fail_json(msg='Community not set when using snmp version 2') if m_args['version'] == "v3": if m_args['username'] == None: module.fail_json(msg='Username not set when using snmp version 3') if m_args['level'] == "authPriv" and m_args['privacy'] == None: module.fail_json( msg='Privacy algorithm not set when using authPriv') if m_args['integrity'] == "sha": integrity_proto = cmdgen.usmHMACSHAAuthProtocol elif m_args['integrity'] == "md5": integrity_proto = cmdgen.usmHMACMD5AuthProtocol if m_args['privacy'] == "aes": privacy_proto = cmdgen.usmAesCfb128Protocol elif m_args['privacy'] == "des": privacy_proto = cmdgen.usmDESPrivProtocol # Use SNMP Version 2 if m_args['version'] == "v2" or m_args['version'] == "v2c": snmp_auth = cmdgen.CommunityData(m_args['community']) # Use SNMP Version 3 with authNoPriv elif m_args['level'] == "authNoPriv": snmp_auth = cmdgen.UsmUserData(m_args['username'], authKey=m_args['authkey'], authProtocol=integrity_proto) # Use SNMP Version 3 with authPriv else: snmp_auth = cmdgen.UsmUserData(m_args['username'], authKey=m_args['authkey'], privKey=m_args['privkey'], authProtocol=integrity_proto, privProtocol=privacy_proto) # Use p to prefix OIDs with a dot for polling p = DefineOid(dotprefix=True) # Use v without a prefix to use with return values v = DefineOid(dotprefix=False) Tree = lambda: defaultdict(Tree) results = Tree() # Getting system description could take more than 1 second on some Dell platform # (e.g. S6000) when cpu utilization is high, increse timeout to tolerate the delay. errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161), timeout=m_args['timeout']), cmdgen.MibVariable(p.sysDescr, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying system description.') for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if current_oid == v.sysDescr: results['ansible_sysdescr'] = decode_hex(current_val) errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.sysObjectId, ), cmdgen.MibVariable(p.sysUpTime, ), cmdgen.MibVariable(p.sysContact, ), cmdgen.MibVariable(p.sysName, ), cmdgen.MibVariable(p.sysLocation, ), lookupMib=False, lexicographicMode=False) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying system infomation.') for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if current_oid == v.sysObjectId: results['ansible_sysobjectid'] = current_val elif current_oid == v.sysUpTime: results['ansible_sysuptime'] = current_val elif current_oid == v.sysContact: results['ansible_syscontact'] = current_val elif current_oid == v.sysName: results['ansible_sysname'] = current_val elif current_oid == v.sysLocation: results['ansible_syslocation'] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.ifIndex, ), cmdgen.MibVariable(p.ifDescr, ), cmdgen.MibVariable(p.ifType, ), cmdgen.MibVariable(p.ifMtu, ), cmdgen.MibVariable(p.ifSpeed, ), cmdgen.MibVariable(p.ifPhysAddress, ), cmdgen.MibVariable(p.ifAdminStatus, ), cmdgen.MibVariable(p.ifOperStatus, ), cmdgen.MibVariable(p.ifHighSpeed, ), cmdgen.MibVariable(p.ipAdEntAddr, ), cmdgen.MibVariable(p.ipAdEntIfIndex, ), cmdgen.MibVariable(p.ipAdEntNetMask, ), cmdgen.MibVariable(p.ifAlias, ), lookupMib=False, lexicographicMode=False) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying interface details') interface_indexes = [] all_ipv4_addresses = [] ipv4_networks = Tree() for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.ifIndex in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex]['ifindex'] = current_val interface_indexes.append(ifIndex) if v.ifDescr in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex]['name'] = current_val if v.ifType in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex]['type'] = current_val if v.ifMtu in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex]['mtu'] = current_val if v.ifSpeed in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex]['speed'] = current_val if v.ifPhysAddress in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex]['mac'] = decode_mac( current_val) if v.ifAdminStatus in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'adminstatus'] = lookup_adminstatus(int(current_val)) if v.ifOperStatus in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'operstatus'] = lookup_operstatus(int(current_val)) if v.ifHighSpeed in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'ifHighSpeed'] = current_val if v.ipAdEntAddr in current_oid: curIPList = current_oid.rsplit('.', 4)[-4:] curIP = ".".join(curIPList) ipv4_networks[curIP]['address'] = current_val all_ipv4_addresses.append(current_val) if v.ipAdEntIfIndex in current_oid: curIPList = current_oid.rsplit('.', 4)[-4:] curIP = ".".join(curIPList) ipv4_networks[curIP]['interface'] = current_val if v.ipAdEntNetMask in current_oid: curIPList = current_oid.rsplit('.', 4)[-4:] curIP = ".".join(curIPList) ipv4_networks[curIP]['netmask'] = current_val if v.ifAlias in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'description'] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.ifInDiscards, ), cmdgen.MibVariable(p.ifOutDiscards, ), cmdgen.MibVariable(p.ifInErrors, ), cmdgen.MibVariable(p.ifOutErrors, ), cmdgen.MibVariable(p.ifHCInOctets, ), cmdgen.MibVariable(p.ifHCOutOctets, ), cmdgen.MibVariable(p.ifInUcastPkts, ), cmdgen.MibVariable(p.ifOutUcastPkts, ), lookupMib=False, lexicographicMode=False) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying interface counters') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.ifInDiscards in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'ifInDiscards'] = current_val if v.ifOutDiscards in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'ifOutDiscards'] = current_val if v.ifInErrors in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex]['ifInErrors'] = current_val if v.ifOutErrors in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'ifOutErrors'] = current_val if v.ifHCInOctets in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'ifHCInOctets'] = current_val if v.ifHCOutOctets in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'ifHCOutOctets'] = current_val if v.ifInUcastPkts in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'ifInUcastPkts'] = current_val if v.ifOutUcastPkts in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'ifOutUcastPkts'] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.entPhysDescr, ), cmdgen.MibVariable(p.entPhysContainedIn, ), cmdgen.MibVariable(p.entPhysClass, ), cmdgen.MibVariable(p.entPhyParentRelPos, ), cmdgen.MibVariable(p.entPhysName, ), cmdgen.MibVariable(p.entPhysHwVer, ), cmdgen.MibVariable(p.entPhysFwVer, ), cmdgen.MibVariable(p.entPhysSwVer, ), cmdgen.MibVariable(p.entPhysSerialNum, ), cmdgen.MibVariable(p.entPhysMfgName, ), cmdgen.MibVariable(p.entPhysModelName, ), cmdgen.MibVariable(p.entPhysIsFRU, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying physical table') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.entPhysDescr in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhysDescr'] = current_val if v.entPhysContainedIn in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhysContainedIn'] = int(current_val) if v.entPhysClass in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhysClass'] = int(current_val) if v.entPhyParentRelPos in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhyParentRelPos'] = int(current_val) if v.entPhysName in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhysName'] = current_val if v.entPhysHwVer in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhysHwVer'] = current_val if v.entPhysFwVer in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhysFwVer'] = current_val if v.entPhysSwVer in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhysSwVer'] = current_val if v.entPhysSerialNum in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhysSerialNum'] = current_val if v.entPhysMfgName in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhysMfgName'] = current_val if v.entPhysModelName in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhysModelName'] = current_val if v.entPhysIsFRU in current_oid: entity_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_physical_entities'][entity_oid][ 'entPhysIsFRU'] = int(current_val) errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.entPhySensorType, ), cmdgen.MibVariable(p.entPhySensorScale, ), cmdgen.MibVariable(p.entPhySensorPrecision, ), cmdgen.MibVariable(p.entPhySensorValue, ), cmdgen.MibVariable(p.entPhySensorOperStatus, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying physical table') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.entPhySensorType in current_oid: sensor_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_sensors'][sensor_oid][ 'entPhySensorType'] = current_val if v.entPhySensorScale in current_oid: sensor_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_sensors'][sensor_oid]['entPhySensorScale'] = int( current_val) if v.entPhySensorPrecision in current_oid: sensor_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_sensors'][sensor_oid][ 'entPhySensorPrecision'] = current_val if v.entPhySensorValue in current_oid: sensor_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_sensors'][sensor_oid][ 'entPhySensorValue'] = current_val if v.entPhySensorOperStatus in current_oid: sensor_oid = int(current_oid.rsplit('.', 1)[-1]) results['snmp_sensors'][sensor_oid][ 'entPhySensorOperStatus'] = current_val interface_to_ipv4 = {} for ipv4_network in ipv4_networks: current_interface = ipv4_networks[ipv4_network]['interface'] current_network = { 'address': ipv4_networks[ipv4_network]['address'], 'netmask': ipv4_networks[ipv4_network]['netmask'] } if not current_interface in interface_to_ipv4: interface_to_ipv4[current_interface] = [] interface_to_ipv4[current_interface].append(current_network) else: interface_to_ipv4[current_interface].append(current_network) for interface in interface_to_ipv4: results['snmp_interfaces'][int( interface)]['ipv4'] = interface_to_ipv4[interface] results['ansible_all_ipv4_addresses'] = all_ipv4_addresses if m_args['is_dell']: errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.ChStackUnitCpuUtil5sec, ), lookupMib=False, lexicographicMode=False) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying CPU busy indeces') for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if current_oid == v.ChStackUnitCpuUtil5sec: results['ansible_ChStackUnitCpuUtil5sec'] = decode_type( module, current_oid, val) errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.lldpLocChassisIdSubtype, ), cmdgen.MibVariable(p.lldpLocChassisId, ), cmdgen.MibVariable(p.lldpLocSysName, ), cmdgen.MibVariable(p.lldpLocSysDesc, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying lldp local system infomation.') for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if current_oid == v.lldpLocChassisIdSubtype: results['snmp_lldp']['lldpLocChassisIdSubtype'] = current_val elif current_oid == v.lldpLocChassisId: results['snmp_lldp']['lldpLocChassisId'] = current_val elif current_oid == v.lldpLocSysName: results['snmp_lldp']['lldpLocSysName'] = current_val elif current_oid == v.lldpLocSysDesc: results['snmp_lldp']['lldpLocSysDesc'] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.lldpLocPortIdSubtype, ), cmdgen.MibVariable(p.lldpLocPortId, ), cmdgen.MibVariable(p.lldpLocPortDesc, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying lldpLocPortTable counters') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.lldpLocPortIdSubtype in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'lldpLocPortIdSubtype'] = current_val if v.lldpLocPortId in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'lldpLocPortId'] = current_val if v.lldpLocPortDesc in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'lldpLocPortDesc'] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.lldpLocManAddrLen, ), cmdgen.MibVariable(p.lldpLocManAddrIfSubtype, ), cmdgen.MibVariable(p.lldpLocManAddrIfId, ), cmdgen.MibVariable(p.lldpLocManAddrOID, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying lldpLocPortTable counters') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.lldpLocManAddrLen in current_oid: address = '.'.join(current_oid.split('.')[13:]) results['snmp_lldp']['lldpLocManAddrLen'] = current_val if v.lldpLocManAddrIfSubtype in current_oid: address = '.'.join(current_oid.split('.')[13:]) results['snmp_lldp']['lldpLocManAddrIfSubtype'] = current_val if v.lldpLocManAddrIfId in current_oid: address = '.'.join(current_oid.split('.')[13:]) results['snmp_lldp']['lldpLocManAddrIfId'] = current_val if v.lldpLocManAddrOID in current_oid: address = '.'.join(current_oid.split('.')[13:]) results['snmp_lldp']['lldpLocManAddrOID'] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.lldpRemChassisIdSubtype, ), cmdgen.MibVariable(p.lldpRemChassisId, ), cmdgen.MibVariable(p.lldpRemPortIdSubtype, ), cmdgen.MibVariable(p.lldpRemPortId, ), cmdgen.MibVariable(p.lldpRemPortDesc, ), cmdgen.MibVariable(p.lldpRemSysName, ), cmdgen.MibVariable(p.lldpRemSysDesc, ), cmdgen.MibVariable(p.lldpRemSysCapSupported, ), cmdgen.MibVariable(p.lldpRemSysCapEnabled, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying lldpLocPortTable counters') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.lldpRemChassisIdSubtype in current_oid: ifIndex = int(current_oid.split('.')[12]) results['snmp_interfaces'][ifIndex][ 'lldpRemChassisIdSubtype'] = current_val if v.lldpRemChassisId in current_oid: ifIndex = int(current_oid.split('.')[12]) results['snmp_interfaces'][ifIndex][ 'lldpRemChassisId'] = current_val if v.lldpRemPortIdSubtype in current_oid: ifIndex = int(current_oid.split('.')[12]) results['snmp_interfaces'][ifIndex][ 'lldpRemPortIdSubtype'] = current_val if v.lldpRemPortId in current_oid: ifIndex = int(current_oid.split('.')[12]) results['snmp_interfaces'][ifIndex][ 'lldpRemPortId'] = current_val if v.lldpRemPortDesc in current_oid: ifIndex = int(current_oid.split('.')[12]) results['snmp_interfaces'][ifIndex][ 'lldpRemPortDesc'] = current_val if v.lldpRemSysName in current_oid: ifIndex = int(current_oid.split('.')[12]) results['snmp_interfaces'][ifIndex][ 'lldpRemSysName'] = current_val if v.lldpRemSysDesc in current_oid: ifIndex = int(current_oid.split('.')[12]) results['snmp_interfaces'][ifIndex][ 'lldpRemSysDesc'] = current_val if v.lldpRemSysCapSupported in current_oid: ifIndex = int(current_oid.split('.')[12]) results['snmp_interfaces'][ifIndex][ 'lldpRemSysCapSupported'] = current_val if v.lldpRemSysCapEnabled in current_oid: ifIndex = int(current_oid.split('.')[12]) results['snmp_interfaces'][ifIndex][ 'lldpRemSysCapEnabled'] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.lldpRemManAddrIfSubtype, ), cmdgen.MibVariable(p.lldpRemManAddrIfId, ), cmdgen.MibVariable(p.lldpRemManAddrOID, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying lldpLocPortTable counters') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.lldpRemManAddrIfSubtype in current_oid: ifIndex = int(current_oid.split('.')[12]) address = '.'.join(current_oid.split('.')[16:]) results['snmp_interfaces'][ifIndex][ 'lldpRemManAddrIfSubtype'] = current_val if v.lldpRemManAddrIfId in current_oid: ifIndex = int(current_oid.split('.')[12]) address = '.'.join(current_oid.split('.')[16:]) results['snmp_interfaces'][ifIndex][ 'lldpRemManAddrIfId'] = current_val if v.lldpRemManAddrOID in current_oid: ifIndex = int(current_oid.split('.')[12]) address = '.'.join(current_oid.split('.')[16:]) results['snmp_interfaces'][ifIndex][ 'lldpRemManAddrOID'] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.cpfcIfRequests, ), cmdgen.MibVariable(p.cpfcIfIndications, ), cmdgen.MibVariable(p.requestsPerPriority, ), cmdgen.MibVariable(p.indicationsPerPriority, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying PFC counters') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.cpfcIfRequests in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'cpfcIfRequests'] = current_val if v.cpfcIfIndications in current_oid: ifIndex = int(current_oid.rsplit('.', 1)[-1]) results['snmp_interfaces'][ifIndex][ 'cpfcIfIndications'] = current_val if v.requestsPerPriority in current_oid: ifIndex = int(current_oid.split('.')[-2]) prio = int(current_oid.split('.')[-1]) results['snmp_interfaces'][ifIndex]['requestsPerPriority'][ prio] = current_val if v.indicationsPerPriority in current_oid: ifIndex = int(current_oid.split('.')[-2]) prio = int(current_oid.split('.')[-1]) results['snmp_interfaces'][ifIndex]['indicationsPerPriority'][ prio] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.csqIfQosGroupStats, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying QoS stats') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.csqIfQosGroupStats in current_oid: ifIndex = int(current_oid.split('.')[-4]) ifDirection = int(current_oid.split('.')[-3]) queueId = int(current_oid.split('.')[-2]) counterId = int(current_oid.split('.')[-1]) results['snmp_interfaces'][ifIndex]['queues'][ifDirection][ queueId][counterId] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.cefcFRUPowerOperStatus, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying FRU') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.cefcFRUPowerOperStatus in current_oid: psuIndex = int(current_oid.split('.')[-1]) results['snmp_psu'][psuIndex]['operstatus'] = current_val errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.ipCidrRouteEntry, ), cmdgen.MibVariable(p.ipCidrRouteStatus, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying CidrRouteTable') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.ipCidrRouteEntry in current_oid: # extract next hop ip from oid next_hop = current_oid.split(v.ipCidrRouteEntry + ".")[1] results['snmp_cidr_route'][next_hop][ 'route_dest'] = current_val if v.ipCidrRouteStatus in current_oid: next_hop = current_oid.split(v.ipCidrRouteStatus + ".")[1] results['snmp_cidr_route'][next_hop]['status'] = current_val if not m_args['is_eos']: errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.sysTotalMemery, ), cmdgen.MibVariable(p.sysTotalFreeMemery, ), cmdgen.MibVariable(p.sysTotalSharedMemory, ), cmdgen.MibVariable(p.sysTotalBuffMemory, ), cmdgen.MibVariable(p.sysCachedMemory, ), lookupMib=False, lexicographicMode=False) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying system infomation.') for oid, val in varBinds: current_oid = oid.prettyPrint() if current_oid == v.sysTotalMemery: results['ansible_sysTotalMemery'] = decode_type( module, current_oid, val) elif current_oid == v.sysTotalFreeMemery: results['ansible_sysTotalFreeMemery'] = decode_type( module, current_oid, val) elif current_oid == v.sysTotalSharedMemory: results['ansible_sysTotalSharedMemory'] = decode_type( module, current_oid, val) elif current_oid == v.sysTotalBuffMemory: results['ansible_sysTotalBuffMemory'] = decode_type( module, current_oid, val) elif current_oid == v.sysCachedMemory: results['ansible_sysCachedMemory'] = decode_type( module, current_oid, val) errorIndication, errorStatus, errorIndex, varTable = cmdGen.nextCmd( snmp_auth, cmdgen.UdpTransportTarget((m_args['host'], 161)), cmdgen.MibVariable(p.dot1qTpFdbEntry, ), ) if errorIndication: module.fail_json(msg=str(errorIndication) + ' querying FdbTable') for varBinds in varTable: for oid, val in varBinds: current_oid = oid.prettyPrint() current_val = val.prettyPrint() if v.dot1qTpFdbEntry in current_oid: # extract fdb info from oid items = current_oid.split(v.dot1qTpFdbEntry + ".")[1].split(".") # VLAN + MAC(6) if len(items) != 7: continue mac_str = "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format( int(items[1]), int(items[2]), int(items[3]), int(items[4]), int(items[5]), int(items[6])) # key must be string key = items[0] + '.' + mac_str results['snmp_fdb'][key] = current_val module.exit_json(ansible_facts=results)
def get_value(IP, PORT, COMMUNITY, OID_ref): errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator( ).getCmd(cmdgen.CommunityData(COMMUNITY), cmdgen.UdpTransportTarget((IP, PORT)), (OID_ref)) return str(varBinds[0][1])
# GETBULK Command Generator from pysnmp.entity.rfc3413.oneliner import cmdgen errorIndication, errorStatus, errorIndex, \ varBindTable = cmdgen.CommandGenerator().bulkCmd( # SNMP v1 # cmdgen.CommunityData('test-agent', 'public', 0), # SNMP v2 # cmdgen.CommunityData('test-agent', 'public'), # SNMP v3 cmdgen.UsmUserData('test-user', 'authkey1', 'privkey1'), cmdgen.UdpTransportTarget(('localhost', 161)), 0, 25, (1,3,6,1,2,1,1) ) if errorIndication: print errorIndication else: if errorStatus: print '%s at %s\n' % ( errorStatus.prettyPrint(), varBindTable[-1][int(errorIndex)-1] ) else: for varBindTableRow in varBindTable: for name, val in varBindTableRow: print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
def receiveRemoteSwitchDataFromSnmpVersion2C(self): # init value count = 0 cmdGen = None self.listRemoteDataFromPort = {} try : # create object for create snmp command cmdGen = cmdgen.CommandGenerator() except Exception as err : print( " Switch ip " + self.switchIp + " 226 terminate because handling run-time error : " + str( err ) ) sys.exit() try : # <snmpv2c> errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget((self.switchIp, 161)), '1.0.8802.1.1.2.1.4.1.1.5', '1.0.8802.1.1.2.1.4.1.1.7' ) if errorIndication: print(errorIndication) count += 1 else: if errorStatus: print('%s at %s' % ( errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex)-1] or '?' ) ) count += 1 else: tempPortID = "" for i in varBindTable: tempPortID = i[1][1].prettyPrint()[2:] # 00000001 # change 00000001 to \x00\x00\x00\x01 packer = struct.Struct('bbbb') binaryPortID = packer.pack( int( tempPortID[0:2] , 16 ) , int( tempPortID[2:4] , 16 ) , int( tempPortID[4:6] , 16 ) , int( tempPortID[6:8] , 16 )) """ key = poistion of active port at recvice remote data in snmp (int : 2) index 0 = datapath id (str : dpid:0000000000000001) index 1 = port id (binary : b'\x00\x00\x00\x01') """ self.listRemoteDataFromPort[str(i[0][0][-2])] = [ i[0][1].prettyPrint() , binaryPortID ] """ print( "key : " + str(i[0][0][-2]) ) print( "index 0 : " + i[0][1].prettyPrint() ) print( "index 1 : " + str(packed_encode) ) """ print("remote port list : ") print(self.listRemoteDataFromPort) return # </snmpv2c> except Exception as err : print( " 277 Switch ip " + self.switchIp + " handling run-time error : " + str( err ) )
async def run_test(context, host, dpName, url): oid = '.1.3.6.1.4.1.89.35.1.112.0' community = 'public' cloudwatch = boto3.client('cloudwatch') while context.get_remaining_time_in_millis() > 3000: # Mark estimated time for next iteration endtime = int(time.time()) + 10 # Create SNMP Request cmdGen = cmdgen.CommandGenerator() errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd( cmdgen.CommunityData(community), cmdgen.UdpTransportTarget((host, 161), timeout=0, retries=0), oid) # Check for errors and print out results snmpres = 0 if errorIndication: print( f'{{ "Description": "DefensePro Health Keep-Alive CPU query", "Name": "{dpName}", "DefensePro IP": "{host}", "SNMP Error": {errorIndication} }}' ) else: if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1] or '?')) else: snmpres = int(varBinds[0][1]) print( f'{{ "Description": "DefensePro Health Keep-Alive CPU query", "Name": "{dpName}", "DefensePro IP": "{host}", "SNMP Result": {snmpres} }}' ) # Run HTTP Test timeout = aiohttp.ClientTimeout(total=1.5) async with aiohttp.ClientSession(timeout=timeout) as session: try: scode = await fetch_HTTP_Response(session, url) print( f'{{ "Description": "DefensePro Health Keep-Alive CPU query", "Name": "{dpName}", "DefensePro IP": "{host}", "Tested URL": "{url}" "HTTP_Result": {scode} }}' ) if scode in [200]: httpres = 0 else: httpres = 10 except Exception as err: print( f'{{ "Description": "DefensePro Health Keep-Alive CPU query", "Name": "{dpName}", "DefensePro IP": "{host}", "Tested URL": "{url}" "HTTP_Result": "{err}" }}' ) httpres = 10 if snmpres > 80 or httpres == 10: lambdares = 10 else: lambdares = 0 response = cloudwatch.put_metric_data(MetricData=[{ 'MetricName': 'DP_KeepAlive_Results', 'Dimensions': [{ 'Name': 'DefensePro_Name', 'Value': dpName }, { 'Name': 'DefensePro_IP', 'Value': host }], 'Unit': 'None', 'Value': lambdares }], Namespace=f'{dpName}') if endtime > int(time.time()) and context.get_remaining_time_in_millis( ) > 10000: await asyncio.sleep(endtime - int(time.time()))
def __init__(self, *args, **kwargs): super(SNMPCollector, self).__init__(*args, **kwargs) if cmdgen is not None: self.snmpCmdGen = cmdgen.CommandGenerator()
def snmp_get(ip,comm,protocol): ''' Collect information from devices and return a dictionary of devices and their link state''' global devices_list, unquerried_neighbors nbridlist = [] nbriplist = [] _device = {} hostname_oid = '1.3.6.1.2.1.1.5' interface_oid = '1.3.6.1.2.1.31.1.1.1.1' if protocol == 'ospf': router_id_oid = ['1.3.6.1.2.1.14.1.1'] neighbor_router_id_oid = ['1.3.6.1.2.1.14.10.1.3'] neighbor_router_ip_oid = ['1.3.6.1.2.1.14.10.1.1'] protocol_ifindex_oid = [] if protocol == 'isis': ''' to match possible oids from juniper systemID, Cisco ciissysID and Juniper Ent systemID ''' router_id_oid = ['1.3.6.1.2.1.138.1.1.1.3', '1.3.6.1.4.1.4874.2.2.38.1.1.1.1.4', '1.3.6.1.4.1.9.10.118.1.1.1.3'] neighbor_router_id_oid = ['1.3.6.1.2.1.138.1.6.1.1.6', '1.3.6.1.4.1.9.10.118.1.6.1.1.6'] neighbor_router_ip_oid = ['1.3.6.1.2.1.138.1.6.3.1.3', '1.3.6.1.4.1.9.10.118.1.6.3.1.3'] protocol_ifindex_oid = ['1.3.6.1.2.1.138.1.3.2.1.2', '1.3.6.1.4.1.9.10.118.1.3.2.1.2'] #Creating command generator object cmdGen = cmdgen.CommandGenerator() ''' Performing SNMP GETNEXT operations on the OIDs The basic syntax of nextCmd: nextCmd(authData, transportTarget, *varNames) The nextCmd method returns a tuple of (errorIndication, errorStatus, errorIndex, varBindTable) ''' hostname = False errIndication,errStatus,errIndex, hostname = cmdGen.nextCmd(cmdgen.CommunityData(comm), cmdgen.UdpTransportTarget((ip, 161)), hostname_oid) for item in hostname: for oid, host in item: _host = str(host) print('%s = %s' % (oid, host)) # check if the hostname is already querried, if it is return for n in range(0, len(devices_list)): if devices_list[n]["Host"] == _host: print(_host, "SKIPPED ALREADY POLLED") return if protocol.lower() != 'ospf': interfaces = False errIndication,errStatus,errIndex, interfaces = cmdGen.nextCmd(cmdgen.CommunityData(comm), cmdgen.UdpTransportTarget((ip, 161)), interface_oid) all_interfaces = {} for item in interfaces: for oid, iface in item: all_interfaces[str(oid)]=str(iface) hostId = False for oid in router_id_oid: errIndication,errStatus,errIndex, hostId = cmdGen.nextCmd(cmdgen.CommunityData(comm), cmdgen.UdpTransportTarget((ip, 161)), oid) if hostId: break for item in hostId: for oid, hostid in item: _host_id ='.'.join([str(octate) for octate in hostid]) varBindNbrTable = False for oid in neighbor_router_id_oid: errIndication,errStatus,errIndex, varBindNbrTable = cmdGen.nextCmd(cmdgen.CommunityData(comm), cmdgen.UdpTransportTarget((ip, 161)), oid) if varBindNbrTable: break for varBindNbrTableRow in varBindNbrTable: for oid, nbrid in varBindNbrTableRow: nbr_r_id = '.'.join([str(octate) for octate in nbrid]) nbridlist.append(nbr_r_id) varBindNbrIpTable = False for oid in neighbor_router_ip_oid: errorIndication, errorStatus, errorIndex, varBindNbrIpTable = cmdGen.nextCmd(cmdgen.CommunityData(comm), cmdgen.UdpTransportTarget((ip, 161)), oid) if varBindNbrIpTable: break for varBindNbrIpTableRow in varBindNbrIpTable: for oid, nbrip in varBindNbrIpTableRow: _ip = '.'.join([str(octate) for octate in nbrip]) try: ip_network(_ip,strict=False) # check if the ip is a valid ipaddress nbriplist.append(_ip) except: continue if protocol.lower() != 'ospf': varIfIndex = False for oid in protocol_ifindex_oid: errIndication,errStatus,errIndex, varIfIndex = cmdGen.nextCmd(cmdgen.CommunityData(comm), cmdgen.UdpTransportTarget((ip, 161)), oid) if varIfIndex: break if varIfIndex: ifnames = [] for item in varIfIndex: for oid, ifindex in item: try: all_interfaces[interface_oid+'.'+str(ifindex)] except KeyError: continue if str(all_interfaces[interface_oid+'.'+str(ifindex)]).lower().startswith('lo'): continue else: ifnames.append(all_interfaces[interface_oid+'.'+str(ifindex)]) ''' remove logical tunnel interfaces configured on the logical system side for junos this is to avoid polling the logical system if the adjacency is between logical and main system ''' if ifnames: for x in range(len(ifnames)): try: if ifnames[x].split('.')[0] == ifnames[x+1].split('.')[0]: if 'lt' in ifnames[x]: ifnames.pop(x+1) except IndexError: pass #Adding data of the polled device in the _device dictionary _device["Host"] = _host _device["HostId"] = _host_id _device["NbrRtrId"] = nbridlist _device["NbrRtrIp"] = nbriplist if protocol.lower() != 'ospf': _device["Interface"] = ifnames for nid in _device["NbrRtrId"]: unquerried_neighbors.append(nid) devices_list.append(_device) return devices_list
def _get(self, key): from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.error import PySnmpError from pysnmp.proto.rfc1905 import NoSuchInstance try: if self.interface.snmp_version == 2: errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator( ).getCmd( cmdgen.CommunityData('exaddos', self.interface.snmp_password), cmdgen.UdpTransportTarget((self.interface.router, 161)), self.collection[key]) elif self.interface.snmp_version == 3: from pysnmp.entity import config mapping_auth = { 'MD5': config.usmHMACMD5AuthProtocol, 'SHA': config.usmHMACSHAAuthProtocol, '': config.usmNoAuthProtocol, } mapping_privacy = { 'DES': config.usmDESPrivProtocol, '3DES': config.usm3DESEDEPrivProtocol, 'AES-128': config.usmAesCfb128Protocol, 'AES-192': config.usmAesCfb192Protocol, 'AES-256': config.usmAesCfb256Protocol, '': config.usmNoPrivProtocol, } user = cmdgen.UsmUserData( self.interface.snmp_user, self.interface.snmp_auth_key, self.interface.snmp_privacy_key, authProtocol=mapping_auth[self.interface.snmp_auth_method], privProtocol=mapping_privacy[ self.interface.snmp_privacy_method]) transport = cmdgen.UdpTransportTarget( (self.interface.router, 161)) errorIndication, errorStatus, errorIndex, varBinds = cmdgen.CommandGenerator( ).getCmd(user, transport, self.collection[key]) # cmdgen.MibVariable('.'.join(str(_) for _ in self.collection[key])) else: raise NotImplemented( 'Feel free to add support for this SNMP version and send us the patch - thanks' ) except PySnmpError: err('SNMP collection failed for %s %s' % (self.name, key)) return None if (errorIndication, errorStatus, errorIndex) == (None, 0, 0): result = varBinds[0][1] if isinstance(result, NoSuchInstance): err('SNMP: %s did not have %s' % (self.name, key)) sys.stderr.flush() return None try: return varBinds[0][1] except AttributeError: err('SNMP: %s did not have %s' % (self.name, key)) return None else: err('SNMP collection failed for %s %s' % (self.name, key)) return None
def __init__(self, snmpCommunity, snmpPort): self.snmpCommunity = snmpCommunity self.snmpPort = snmpPort self.switches = {} self.snmpCmd = cmdgen.CommandGenerator()
def main(warning, critical, debug, interface, type, community="public", host="localhost", port=161, *metrics): if debug: print "Arguments as parsed by plac:" print pprint.pprint(locals()) modules = MibBuilder().loadModules('RFC1213-MIB') rfc1213 = MibViewController(modules) values = {} oids = [] if not interface: print "CRITICAL: No interface specified!" sys.exit(EXITCODE['CRITICAL']) if not metrics: print "CRITICAL: No metrics specified!" sys.exit(EXITCODE['CRITICAL']) for metric in metrics: if metric not in METRIC_LIST: print "CRITICAL: %s not in metric list!" % metric sys.exit(EXITCODE['CRITICAL']) oid = rfc1213.getNodeNameByDesc(metric)[0] oids.append(oid + (int(interface),)) try: cmd = cmdgen.CommandGenerator() errorIndication, errorStatus, \ errorIndex, table = cmd.getCmd( cmdgen.CommunityData('nagios', community), cmdgen.UdpTransportTarget((host, port)), *oids) if errorIndication: print "CRITICAL: %s" % errorIndication sys.exit(EXITCODE['CRITICAL']) else: if errorStatus: print "CRITICAL: %s" % errorStatus.prettyPrint() sys.exit(EXITCODE['CRITICAL']) else: for row in table: oid, value = row p_oid, p_label, p_suffix = rfc1213.getNodeName(oid) p_type = '.'.join(p_label[9:]) p_interface = '.'.join(str(i) for i in p_suffix) # TODO: Add code path to print interface list if debug: if p_type == 'ifDescr': print "%s.%s: %s" % (p_type, p_interface, value) if p_type in metrics and p_interface == interface: if debug: print "%s.%s: %s" % (p_type, p_interface, value) values[p_type] = value except socket.gaierror: print "CRITICAL: Unable to connect to the server." sys.exit(EXITCODE['CRITICAL']) status = 3 if not warning and not critical: # Informational only, i.e. for pnp4nagios status = 0 elif type in ['be-higher-than', 'be-lower-than']: warning = float(warning) critical = float(critical) statuses = [] for key, value in values.items(): value = float(value) statuses.append(test_in_range(value, warning, critical, type == 'be-lower-than')) status = max(statuses) elif type == 'within-range': # Ranges like 7.1-8.9. Overkill? Maybe. # TODO: Add support for Nagios-style ranges. re_range = re.compile("(\d+\.{0,1}\d*)[\- ]+(\d+\.{0,1}\d*)") try: warning_min, warning_max = map(float, re_range.search(warning).groups()) critical_min, critical_max = map(float, re_range.search(critical).groups()) except: print "%s CRITICAL: Error parsing arguments." % SERVICE sys.exit(EXITCODE['CRITICAL']) value = float(value) status = max(test_in_range(value, warning_min, critical_min, False), test_in_range(value, warning_max, critical_max)) elif type in ['must-have-regex', 'must-not-have-regex']: re_warning = re_critical = None try: if warning: re_warning = re.compile(warning) if critical: re_critical = re.compile(critical) except: print "%s CRITICAL: Your regular expression was invalid." % SERVICE sys.exit(2) status = 0 if re_warning: if (re_warning.search(value) is not None) == \ (type == 'must-not-have-regex'): status = 1 if re_critical: if (re_critical.search(value) is not None) == \ (type == 'must-not-have-regex'): status = 2 if debug: pprint.pprint(values) print "%s %s: %s|%s" % (SERVICE, STATUSES[status], format_values(values), format_perfdata(metrics, values, warning, critical)) sys.exit(status)
def getPortFromSnmpVersion2C(self, mininetOption): # init value count = 0 cmdGen = None # list port dictPort = {} try: # create object for create snmp command cmdGen = cmdgen.CommandGenerator() except Exception as err: print(" 94 Switch ip " + self.switchIp + " terminate because handling run-time error : " + str(err)) sys.exit() while count < self.numberOfRetransmission: try: # connect to snmp at switch errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget((self.switchIp, 161)), '1.0.8802.1.1.2.1.3.7.1.3', '1.0.8802.1.1.2.1.3.7.1.4') if errorIndication: print(errorIndication) count += 1 else: if errorStatus: print( '%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?')) count += 1 else: # init value #index = 1 # number of port if mininetOption == 1 and len(varBindTable) > 0: del varBindTable[len(varBindTable) - 1] # check number of port should > 0 if (len(varBindTable) > 0): for i in varBindTable: # mac address tempHwAddr = i[0][1].prettyPrint() tempHwAddr = tempHwAddr[2:len(tempHwAddr)] if (len(tempHwAddr) != 12): print( "Error invalid mac address from local port in snmp" ) else: tempHwAddr = tempHwAddr[ 0:2] + ":" + tempHwAddr[ 2:4] + ":" + tempHwAddr[ 4:6] + ":" + tempHwAddr[ 6:8] + ":" + tempHwAddr[ 8: 10] + ":" + tempHwAddr[ 10:12] tempPPort = PPort(i[0][0][-1], tempHwAddr, i[1][1].prettyPrint(), 0, 0, 192, 0, 0, 0) dictPort[str( i[0][0][-1] )] = tempPPort # type interger chage to str """ print("key : " + str(i[0][0][-1]) ) print("item : " + tempPPort ) """ """ key : poistion of active port in snmp (2) item : PPort(object) """ #index += 1 return dictPort else: print( " 159 Switch ip " + self.switchIp + " terminate because : switch doesn't have active port please snmp" ) sys.exit() except Exception as err: count += 1 print(" 165 Switch ip " + self.switchIp + " handling run-time error : " + str(err)) print(" Switch ip " + self.switchIp + " terminate because : it has problem about snmp ") sys.exit()
def generate_json(snmp_monitor): """This function will take the device config and raw data (if any) from the snmp_monitor and output JSON data formatted for the StatusBar iPad App""" # Create the pysnmp SNMP CommandGenerator, used to get SNMP data cmd_gen = cmdgen.CommandGenerator() try: # ===============CLT NetBotz1 data error_indication, error_status, error_index, var_binds = cmd_gen.getCmd( cmdgen.CommunityData(SNMP_COMMUNITY), cmdgen.UdpTransportTarget(('10.4.50.235', 161)), "1.3.6.1.4.1.5528.100.4.1.1.1.9.636159851", # Room Temp (Rack 4 Top) "1.3.6.1.4.1.5528.100.4.1.1.1.9.3031356659", # Hot Aisle (HAC 2 Temp) "1.3.6.1.4.1.5528.100.4.1.2.1.8.1744856019" # Humidity ) if error_indication or error_status: clt_temperature = "XX" hot_aisle = "XX" clt_humidity = "XX" else: clt_temperature = int(var_binds[0][1]) hot_aisle = int(var_binds[1][1]) clt_humidity = int(var_binds[2][1]) # ===============CLT NetBotz2 data error_indication, error_status, error_index, var_binds = cmd_gen.getCmd( cmdgen.CommunityData(SNMP_COMMUNITY), cmdgen.UdpTransportTarget(('10.4.50.236', 161)), "1.3.6.1.4.1.5528.100.4.1.1.1.9.2628357572", # Cold Aisle (Rack 3 bottom Temp) ) if error_indication or error_status: cold_aisle = "XX" else: cold_aisle = int(var_binds[0][1]) # ============ CLT Symmetra data error_indication, error_status, error_index, var_binds = cmd_gen.getCmd( cmdgen.CommunityData(SNMP_COMMUNITY), cmdgen.UdpTransportTarget(("10.4.50.230", 161)), "1.3.6.1.4.1.318.1.1.1.2.2.3.0", # UPS Runtime "1.3.6.1.4.1.318.1.1.1.9.3.3.1.7.1.1.1", # UPS Load Phase 1 "1.3.6.1.4.1.318.1.1.1.9.3.3.1.7.1.1.2", # UPS Load Phase 2 "1.3.6.1.4.1.318.1.1.1.9.3.3.1.7.1.1.3" # UPS Load Phase 3 ) if error_indication or error_status: clt_runtime = "XX" clt_load = "XX" else: clt_runtime = int( var_binds[0] [1]) / 100 / 60 # Convert TimeTicks to Seconds to minutes clt_runtime = int(clt_runtime) load_p1 = int(var_binds[1][1]) load_p2 = int(var_binds[2][1]) load_p3 = int(var_binds[3][1]) clt_load = (load_p1 + load_p2 + load_p3) / 1000 # Convert to kVA clt_load = round(clt_load, 1) # ===============RH APC SMARTUPS (Must be SNMPv1) error_indication, error_status, error_index, var_binds = cmd_gen.getCmd( cmdgen.CommunityData(SNMP_COMMUNITY, mpModel=0), # mpModel=0 for SNMPv1 cmdgen.UdpTransportTarget(("10.3.1.240", 161)), "1.3.6.1.4.1.318.1.1.10.1.3.3.1.4.1", # Temperature "1.3.6.1.4.1.318.1.1.10.1.3.3.1.6.1", # Humidity "1.3.6.1.4.1.318.1.1.1.4.2.3.0", # UPS Load Percent "1.3.6.1.4.1.318.1.1.1.2.2.3.0" # UPS Runtime ) if error_indication or error_status: rh_temperature = "XX" rh_humidity = "XX" rh_load = "XX" rh_runtime = "XX" else: rh_temperature = int(var_binds[0][1]) rh_humidity = int(var_binds[1][1]) rh_load = int(var_binds[2][1]) rh_runtime = int( var_binds[3] [1]) / 100 / 60 # Convert TimeTicks to Seconds to minutes rh_runtime = int(rh_runtime) # ===============TRI APC SMARTUPS (Must be SNMPv1) error_indication, error_status, error_index, var_binds = cmd_gen.getCmd( cmdgen.CommunityData("n8bez5b9rdeabik", mpModel=0), # mpModel=0 for SNMPv1 cmdgen.UdpTransportTarget(("10.10.1.13", 161)), "1.3.6.1.4.1.318.1.1.10.1.3.3.1.4.1", # Temperature "1.3.6.1.4.1.318.1.1.10.1.3.3.1.6.1", # Humidity "1.3.6.1.4.1.318.1.1.1.4.2.3.0", # UPS Load Percent "1.3.6.1.4.1.318.1.1.1.2.2.3.0" # UPS Runtime ) if error_indication or error_status: tri_temperature = "XX" tri_humidity = "XX" tri_load = "XX" tri_runtime = "XX" else: tri_temperature = int(var_binds[0][1]) tri_humidity = int(var_binds[1][1]) tri_load = int(var_binds[2][1]) tri_runtime = int( var_binds[3] [1]) / 100 / 60 # Convert TimeTicks to Seconds to minutes tri_runtime = int(tri_runtime) # =========== Create Dictionary for JSON output snmp_data = { "cold_aisle": cold_aisle, "hot_aisle": hot_aisle, "clt_temp": clt_temperature, "clt_humidity": clt_humidity, "clt_load": clt_load, "clt_runtime": clt_runtime, "tri_temp": tri_temperature, "tri_humidity": tri_humidity, "tri_load": tri_load, "tri_runtime": tri_runtime, "rh_temp": rh_temperature, "rh_humidity": rh_humidity, "rh_load": rh_load, "rh_runtime": rh_runtime } except Exception as error: snmp_data = { "error": "There was a problem accessing SNMP data:" + error.message } snmp_monitor.json = json.dumps(snmp_data) if __debug__: print snmp_monitor.json return
def getRemoteSwitchDataFromSnmpVersion2C(self): # init value count = 0 cmdGen = None dictRemoteSwitchDataFromPort = {} try: # create object for create snmp command cmdGen = cmdgen.CommandGenerator() except Exception as err: print(" Switch ip " + self.switchIp + " 226 terminate because handling run-time error : " + str(err)) sys.exit() try: # <snmpv2c> errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd( cmdgen.CommunityData('public'), cmdgen.UdpTransportTarget( (self.switchIp, 161)), '1.0.8802.1.1.2.1.4.1.1.5', '1.0.8802.1.1.2.1.4.1.1.7', '1.0.8802.1.1.2.1.4.1.1.8', '1.0.8802.1.1.2.1.4.1.1.4', '1.0.8802.1.1.2.1.4.1.1.6') if errorIndication: print(errorIndication) count += 1 else: if errorStatus: print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBindTable[-1][int(errorIndex) - 1] or '?')) count += 1 else: #init value tempPortID = "" chassisIdSubType = "" portIdSubType = "" firstData = None secondData = None status = None for i in varBindTable: chassisIdSubType = i[3][1].prettyPrint() portIdSubType = i[4][1].prettyPrint() if chassisIdSubType == "7" and portIdSubType == "2": firstData = i[0][1].prettyPrint() tempPortID = i[1][1].prettyPrint()[2:] # 00000001 # change 00000001 to \x00\x00\x00\x01 packer = struct.Struct('bbbb') secondData = packer.pack(int(tempPortID[0:2], 16), int(tempPortID[2:4], 16), int(tempPortID[4:6], 16), int(tempPortID[6:8], 16)) status = True elif chassisIdSubType == "4" and portIdSubType == "3": firstData = i[0][1].prettyPrint() secondData = i[2][1].prettyPrint() status = False """ key = poistion of active port at recvice remote data in snmp (int : 2) index 0 = datapath id (str : dpid:0000000000000001) index 1 = port no (binary : b'\x00\x00\x00\x01') index 2 = check status (datapath_id, port_no) or (hw_addr, hw_desc) """ dictRemoteSwitchDataFromPort[str( i[0][0][-2])] = [firstData, secondData, status] """printedit""" """ print("dictRemoteSwitchDataFromPort : ") print( "key : " + str(i[0][0][-2]) ) print( "index 0 : " + dictRemoteSwitchDataFromPort[str(i[0][0][-2])][0] ) print( "index 1 : " + str(dictRemoteSwitchDataFromPort[str(i[0][0][-2])][1]) ) print( "index 2 : " + str(dictRemoteSwitchDataFromPort[str(i[0][0][-2])][2]) ) """ #print("remote port list : ") #print(dictRemoteSwitchDataFromPort) return dictRemoteSwitchDataFromPort # </snmpv2c> except Exception as err: print(" 277 Switch ip " + self.switchIp + " handling run-time error : " + str(err))
#!/usr/bin/env python3 # -*- coding=utf-8 -*- # 本脚由亁颐堂现任明教教主编写,用于乾颐盾Python课程! # 教主QQ:605658506 # 亁颐堂官网www.qytang.com # 教主技术进化论拓展你的技术新边疆 # https://ke.qq.com/course/271956?tuin=24199d8a from pysnmp.entity.rfc3413.oneliner import cmdgen import sys from io import StringIO cmdGen = cmdgen.CommandGenerator() def snmpv3_getnext(ip='', user='', hash_meth=None, hash_key=None, cry_meth=None, cry_key=None, oid='', num=1): # usmHMACMD5AuthProtocol - MD5 hashing # usmHMACSHAAuthProtocol - SHA hashing # usmNoAuthProtocol - no authentication # usmDESPrivProtocol - DES encryption # usm3DESEDEPrivProtocol - triple-DES encryption # usmAesCfb128Protocol - AES encryption, 128-bit # usmAesCfb192Protocol - AES encryption, 192-bit # usmAesCfb256Protocol - AES encryption, 256-bit
# -*- coding: utf-8 -*-