def getStatus(): checkprev = 0 i = 1 while True: try: linkname = snmp_get('1.3.6.1.4.1.3845.31.4.2.2.15.2.1.3.' + str(i), hostname=ip, version=3, security_level="auth_without_privacy", security_username=username, auth_protocol="SHA", auth_password=password, privacy_protocol="AES", privacy_password=password) state = snmp_get('1.3.6.1.4.1.3845.31.4.2.2.15.2.1.4.' + str(i), hostname=ip, version=3, security_level="auth_without_privacy", security_username=username, auth_protocol="SHA", auth_password=password, privacy_protocol="AES", privacy_password=password) except: print('CRITICAL | Connection Error') sys.exit(2) if state.value != str(0): if state.value == str(1): state.value = 'DISABLED' elif state.value == str(2): state.value = 'DEAD' elif state.value == str(3): state.value = 'BAD' elif state.value == str(4): state.value = 'GOOD' linkstatus.update({linkname.value:state.value}) if checkprev == len(linkstatus): break else: checkprev += 1 else: break i += 1 return linkstatus
def pulloid(ip): global counter counter = 0 desc = str( snmp_get('iso.3.6.1.2.1.1.1.0', hostname=str(ip), community='public', version=2)).split("'")[1] if "Firmware Version" in desc and "Build" in desc: fwv = desc.replace("Version ", "Version:").replace(" Build ", ":Build:").split(':')[1] bnum = desc.replace("Version ", "Version:").replace(" Build ", ":Build:").split(':')[3] model = str( snmp_get('iso.3.6.1.2.1.1.5.0', hostname=str(ip), community='public', version=2)).split("'")[1].replace(" (contains binary)", "") with open("ep-snmp-details.csv", "a+") as f: f.write( str(ip) + "," + model + "," + fwv + "," + bnum + "," + desc + "\n") print '[+] Found "' + model + '" Mercury OEM at ' + str(ip) counter += 1
def getStatus(): checkprev = 0 i = 1 while True: try: linkname = snmp_get('1.3.6.1.4.1.3845.31.4.2.2.15.2.1.3.' + str(i), hostname=ip, community=community, version=2) state = snmp_get('1.3.6.1.4.1.3845.31.4.2.2.15.2.1.4.' + str(i), hostname=ip, community=community, version=2) except: print('CRITICAL | Connection Error') sys.exit(2) if state.value != str(0): if state.value == str(1): state.value = 'DISABLED' elif state.value == str(2): state.value = 'DEAD' elif state.value == str(3): state.value = 'BAD' elif state.value == str(4): state.value = 'GOOD' linkstatus.update({linkname.value: state.value}) if checkprev == len(linkstatus): break else: checkprev += 1 else: break i += 1 return linkstatus
def pulloid(ip): global counter counter = 0 desc = str(snmp_get('iso.3.6.1.2.1.1.1.0', hostname=str(ip), community='public', version=2)).split("'")[1] if "Firmware Version" in desc and "Build" in desc: fwv = desc.replace("Version ", "Version:").replace(" Build ", ":Build:").split(':')[1] bnum = desc.replace("Version ", "Version:").replace(" Build ", ":Build:").split(':')[3] model = str(snmp_get('iso.3.6.1.2.1.1.5.0', hostname=str(ip), community='public', version=2)).split("'")[1].replace(" (contains binary)", "") with open("ep-snmp-details.csv","a+")as f: f.write(str(ip)+","+model+","+fwv+","+bnum+","+desc+"\n") print '[+] Found "'+model+'" Mercury OEM at '+str(ip) counter += 1
def get_SNMP_task(agente, oid_1, oid_2): r_1 = 0 r_2 = 0 try: r_1 = (snmp_get(oid_1, hostname=agente.Ip, community=agente.Comunidad, version=agente.Protocolo)).value r_2 = (snmp_get(oid_2, hostname=agente.Ip, community=agente.Comunidad, version=agente.Protocolo)).value except Exception: r_1 = 'error' r_2 = 'error' return r_1, r_2
def InitScript(Data): logger.info("Récupération des modèles d'IRD en cours...") Dict = {} for i in range(1, 36): Position = "ird" + str(i) Model = "model" + str(i) try: s = snmp_get(Data['IRDModel'], hostname=Data[Position], community='private', version=1) except: logger.error( "Impossible de communiquer avec : {} !!".format(Position)) Dict[Model] = 'Inconnu' continue m = re.search(r'(value=)\'(.*)\'\ (.*)', str(s)) for item in Data['SupportedModels']: if re.search(item[:3], m.group(2), re.IGNORECASE): Dict[Model] = item break elif re.search(r'armv7', m.group(2), re.IGNORECASE): Dict[Model] = item break else: Dict[Model] = 'NoMatch' if Dict[Model] == 'NoMatch': logger.error( "Impossible de déterminer le modèle de : {} !!".format( Position)) Dict[Model] = 'Inconnu' logger.debug(Dict) logger.info("Terminé.") return Dict
def getUpstreamErrors(cmts, cmIndex): cmUsErrors = ".1.3.6.1.2.1.10.127.1.3.3.1.12." + str(cmIndex) cmUsErrorsData = snmp_get(cmUsErrors, hostname=cmts, community='private', version=2) return cmUsErrorsData.value
def getCmIfIndex(cmts, cmIndex): getCmIfIndex = ".1.3.6.1.2.1.10.127.1.3.3.1.5." + str(cmIndex) getCmIfIndexData = snmp_get(getCmIfIndex, hostname=cmts, community='private', version=2) return getCmIfIndexData.value
def get_port_status(self, port): """ Показывает статус указанного порта (включен или выключен) :param port: :return: MAC адрес or False (в случае если невозможно получить мак адрес с данного порта) """ current_function = 'Switch.get_port_status' try: port_status = snmp_get('IF-MIB::ifOperStatus.{}'.format(str(port)), hostname=self.host, community='orion_comm', version=2) except exceptions.EasySNMPTimeoutError: self.log.error('Хост {} - недоступен'.format(self.host)) return False else: if port_status.value == 'NOSUCHINSTANCE': self.log.error('{}: Отсутствует {} порт у свитча {}'.format( current_function, port, self.host)) return False status = port_status.value if status == '1': return True return False
def collect_power_usage_info(): config = settings.PLUGINS_CONFIG["axians_netbox_pdu"] devices = Device.objects.filter().exclude( device_type__pduconfig__isnull=True).exclude(primary_ip4__isnull=True) logging.info("Start: Collecting Power Usage Information") results = [] for device in devices: try: power_usage = snmp_get( device.device_type.pduconfig.power_usage_oid, hostname=str(device.primary_ip4.address.ip), community=config["snmp_read"], version=2, ) except EasySNMPError as err: logging.error( f"Failed to get power usage status for {device.name}: {err}.") raise pdu_status = PDUStatus.objects.update_or_create( device=device, defaults={"power_usage": power_usage.value}) data = {device.name: power_usage.value} results.append(data) logging.info("FINISH: Collecting Power Usage Information") return results
def getCmIndex(macDottedDecimal, cmts): cmIndex = ".1.3.6.1.2.1.10.127.1.3.7.1.2" + macDottedDecimal cmIndexData = snmp_get(cmIndex, hostname=cmts, community='private', version=2) cmIndexData = cmIndexData.value return cmIndexData
def run(parameters): try: return snmp_get(parameters["object"], hostname=parameters["agent"], community=parameters["community"], version=2).value except Exception: return "Something went wrong."
def getUpstreamErrors(mac, cmts): ## This function will: ## Convert the MAC into dotted decimal ## Get the CM index by polling the CMTS ## Get the Upstream Error counter by polling the CMTS ## Oids #print "Now getting US INFO" cmIndex = ".1.3.6.1.2.1.10.127.1.3.7.1.2" ## Append the dotted decimal mac to the string to get the value upHec = ".1.3.6.1.2.1.10.127.1.3.3.1.12." ## Append the cmIndex to the string to get the value #print "Converting", mac ,"to decimal" ## Easy to convert hex in Python. result = int("0xff", 16) mac = mac.split(':') ## Need to convert each hextet to decimal and then build the dotted decimal result. Might be a better way to do this, can't find a function. ## Break up the MAC address into hextets H stands for Hextet macH0 = mac[0] macH1 = mac[1] macH2 = mac[2] macH3 = mac[3] macH4 = mac[4] macH5 = mac[5] ## Convert each hextet to decimal dec0 = int(macH0, 16) dec1 = int(macH1, 16) dec2 = int(macH2, 16) dec3 = int(macH3, 16) dec4 = int(macH4, 16) dec5 = int(macH5, 16) #print dec0, dec1, dec2, dec3, dec4, dec5 macDottedDecimal = "." + str(dec0) + "." + str(dec1) + "." + str( dec2) + "." + str(dec3) + "." + str(dec4) + "." + str(dec5) #print macDottedDecimal cmIndex = ".1.3.6.1.2.1.10.127.1.3.7.1.2" + macDottedDecimal cmIndexData = snmp_get(cmIndex, hostname=cmts, community='private', version=2) cmIndexData = cmIndexData.value cmUsErrors = ".1.3.6.1.2.1.10.127.1.3.3.1.12." + str(cmIndexData) cmUsErrorsData = snmp_get(cmUsErrors, hostname=cmts, community='private', version=2) return cmUsErrorsData.value
def get_location(hostname): """Requests and parses the snmp location from a hostname or address. The expected format is: /snmp set location=47.1234,-121.1234""" try: loc = snmp_get(OID_LOCATION, hostname=hostname, **SNMP_ARGS) lat, lon = loc.value.split(',')[0:2] return float(lat), float(lon) except (ValueError, EasySNMPConnectionError, EasySNMPTimeoutError): return None, None
def getJuniperData(ip, pid): data = {} data["speed"] = int( snmp_get(ifHighSpeed + "." + str(pid), hostname=ip, community='cacti', version=2).value) data["in"] = int( snmp_get(ifHCInOctets + "." + str(pid), hostname=ip, community='cacti', version=2).value) data["out"] = int( snmp_get(ifHCOutOctets + "." + str(pid), hostname=ip, community='cacti', version=2).value) return data
def get(self, items: list): result = list() for oid in items: r = snmp_get(oid, hostname=self.host, community=self.community_read, version=self.version) result.append((oid, r.value)) return result
def statsnmp(_oid): hostname = sys.argv[1] # IP address is IP of Hytera repeater _snmp_response = snmp_get(_oid, hostname=hostname, community='public', version=1) # return is string not int! return (_snmp_response.value)
def get_location(hostname): """Requests and parses the snmp location from a hostname or address. The expected format is: /snmp set location=47.1234,-121.1234""" try: loc = snmp_get(OID_LOCATION, hostname=hostname, **SNMP_ARGS) lat, lon = loc.value.split(',')[0:2] return float(lat), float(lon) except (ValueError, EasySNMPConnectionError, EasySNMPTimeoutError): return None, None
def getData(ip, port): # returns speed, in, out data = {} data["speed"] = int( snmp_get(ifSpeed64 + "." + port, hostname=ip, community='cacti', version=2).value) data["in"] = int( snmp_get(inOctets64 + "." + port, hostname=ip, community='cacti', version=2).value) data["out"] = int( snmp_get(outOctets64 + "." + port, hostname=ip, community='cacti', version=2).value) return data
def my_snmp_get(args, oid, use_sprint_value=False): try: retval = snmp_get(oid, hostname=args.H, community=args.C, version=2, use_sprint_value=use_sprint_value) except (EasySNMPConnectionError, EasySNMPTimeoutError) as err: snmp_err(err) return retval
def snmp_get(self, oid, host_name): mib_object = easysnmp.snmp_get( oid, hostname=host_name, version=3, security_level='auth_with_privacy', security_username=self.env_vars.get_user_name(), privacy_protocol='AES', privacy_password=self.env_vars.get_priv_pass(), auth_protocol='SHA', auth_password=self.env_vars.get_auth_pass()) return mib_object.value
def searchPortIdFromFdbPortandIp(dot1dTpFdbPort, ip, db, community): temp = snmp_get("1.3.6.1.2.1.17.1.4.1.2."+dot1dTpFdbPort, hostname=ip, community=community, version=2) postIndex = temp.value cursor = db.cursor() exe = "SELECT portId FROM ifTable WHERE address = %s AND ifIndex = %s ;" % ("\"" + ip +"\"", "\"" + postIndex +"\"") cursor.execute(exe) result = cursor.fetchone() if result == None: logging.warning("No found portID from FdbPort %s and Ip %s", dot1dTpFdbPort, ip) return None return result[0] return result[0]
def poll(host): try: get = easysnmp.snmp_get(oids, hostname=host, version=version, community=community, retries=retries, timeout=timeout) except Exception as err: return if get: return _convertToDict(get)
def getNames(ip): ports = [] for i in range(1, 999): res = str( snmp_get(ifDescr + "." + str(i), hostname=ip, community='cacti', version=2).value) if not "NOSUCHINSTANCE" in res: if "xe" in res or "ge" in res: #print ("ID: {} Data: {}".format(i,res)) ports.append((i, res)) return ports
def searchportIdFromFdbPortandIp(dot1dTpFdbPort, ip, db, community): # dot1dTpFdbPort give you the number of port, from that, you # need to find the index of that port, compare with ifTable to file portID temp = snmp_get("1.3.6.1.2.1.17.1.4.1.2."+dot1dTpFdbPort, hostname=ip, community=community, version=2) postIndex = temp.value cursor = db.cursor() exe = "SELECT portId, deviceId, address, ifPhysAddress FROM ifTable WHERE address = %s AND ifIndex = %s ;" % ("\"" + ip +"\"", "\"" + postIndex +"\"") cursor.execute(exe) result = cursor.fetchone() if result == None: return False # print result return result
def get_SNMP(agentes, listaGet): respuesta = [] for agente in agentes: resultado = [] for elemento in listaGet: try: resultado.append((snmp_get(elemento, hostname=agente.Ip, community=agente.Comunidad, version=agente.Protocolo)).value) except Exception: resultado.append('error') respuesta.append([agente.id, resultado]) return respuesta
def poll(oids, host, community, **kwargs): version = kwargs.get('version', 2) retries = kwargs.get('retries', 1) timeout = kwargs.get('timeout', 1) try: get = easysnmp.snmp_get(oids, hostname=host, version=version, community=community, retries=retries, timeout=timeout) except Exception as err: return if get: return _convertToDict(get)
def my_snmp_get_v3(args, oid, context="", use_sprint_value=False): try: retval = snmp_get(oid, hostname=args.H, security_level=args.l, security_username=args.u, auth_protocol=args.a, auth_password=args.A, privacy_protocol=args.x, privacy_password=args.X, context=context, version=3, use_sprint_value=use_sprint_value) except (EasySNMPConnectionError, EasySNMPTimeoutError) as err: snmp_err(err) return retval
def net_parse(networks): routers = list() dbg_list = list() name_list = list() for item in networks: IP_object = IPNetwork(item) NET_list = list(IP_object.subnet(24)) for subnet in NET_list: router = str(subnet[1]) if not ping(router, 0.1): continue try: oid = '1.3.6.1.2.1.1.5.0' name = snmp_get(oid, hostname=router, community='public', version=1) dbg_list.append(name.value) if name.value not in name_list: name_list.append(name.value) routers.append([router]) except Exception: continue return routers
for j in range(4, len(cla)): alloids.append(cla[j]) for z in range(1, len(cla) - 4): globals()['a%s' % z] = 0 globals()['b%s' % z] = 0 for i in range(0, int(cla[3]) + 1): x1 = time.time() if i != 0: print int(time.time()), '|', #print time for every sample get_list = snmp_get(alloids, hostname=h, remote_port=p, community=c, version=2, timeout=1, retries=1) #storing all requests in list for y in range(0, len(get_list)): if get_list[y].value == "NOSUCHINSTANCE" or get_list[ y].value == "NOSUCHOBJECT": get_list.remove(get_list[y]) # remove if there is wrong oid for x in range(1, len(get_list)): #caluculate rate globals()['c%s' % x] = get_list[x].value globals()['d%s' % x] = get_list[x].snmp_type globals()['t%s' % x] = time.time() if i != 0: diff = ((int(globals()['c%s' % x]) - globals()['a%s' % x])) tdiff = round(globals()['t%s' % x] - globals()['b%s' % x], 1)
Ts = float(1 / Fs) o1 = ['1.3.6.1.2.1.1.3.0'] o2 = sys.argv[4:len(sys.argv)] oids = o1 + o2 l1 = [] v1 = [] l2 = [] v2 = [] T_start = time.clock() n = 1 try: sent_time1 = time.time() req1 = snmp_get(oids, hostname=ip, community=commun, version=2, timeout=5, retries=1) recv_time1 = time.time() for item in req1: a1 = item.value l1.append(a1) counter_type = item.snmp_type v1 = [s for s in l1[:] if s.isdigit()] if v1: val1 = map(int, v1[1:]) if Fs > 1: t1 = float(v1[0]) / 100 else: t1 = int(v1[0]) / 100
def check_if_out_errors(host, community, interface): system_items = snmp_walk('IF-MIB::ifName', hostname=host, community=community, version=2) found = False for item in system_items: if item.value == interface: oid = item.oid value = item.value oid_index = item.oid_index found = True if found: if_in_errors = snmp_get('IF-MIB::ifOutErrors.' + oid_index, hostname=host, community=community, version=2) file_name = "{}.{}.out_errors.txt".format(host, value) try: # OPEN FILE fo = open("/tmp/" + file_name, "r+") # READ LAST VALUE last_value = long(fo.read()) # PIC THE ACTUAL VALUE actual_value = long(if_in_errors.value) # COMPARE THE VALUES if actual_value > last_value: # TRUNCATE FILE CONTENT AND WRITE NEW CONTENT fo.seek(0) fo.truncate() fo.write(str(actual_value)) # PRINT MESSAGE AND EXIT print "Critical - Interface {} is increasing errors".format( interface) sys.exit(2) else: # TRUNCATE FILE CONTENT AND WRITE NEW CONTENT fo.seek(0) fo.truncate() fo.write(str(actual_value)) # PRINT MESSAGE AND EXIT print "OK - Interface {} is not increasing errors".format( interface) sys.exit(0) except IOError: # CREATE FILE AND WRITE THE FIRST VALUE fo = open("/tmp/" + file_name, "w+") fo.write(if_in_errors.value) # CLOSE FILE fo.close() # RETURN OK - FILE CREATED print "OK - Interface {} is not increasing errors".format( interface) sys.exit(0) else: print "Unknown - Interface not found" sys.exit(3)