def get_neighbors(hostname): macs = [i.value for i in snmp_walk(OID_NEIGHBOR_MAC, hostname=hostname, **SNMP_ARGS)] macs = [":".join("%02X" % i for i in map(ord, mac)) for mac in macs] ips = [i.value for i in snmp_walk(OID_NEIGHBOR_IP, hostname=hostname, **SNMP_ARGS)] ids = [i.value for i in snmp_walk(OID_NEIGHBOR_ID, hostname=hostname, **SNMP_ARGS)] values = zip(ips, ids) return dict(zip(macs, values))
def get_neighbors(hostname): macs = [ i.value for i in snmp_walk(OID_NEIGHBOR_MAC, hostname=hostname, **SNMP_ARGS) ] macs = [":".join("%02X" % i for i in map(ord, mac)) for mac in macs] ips = [ i.value for i in snmp_walk(OID_NEIGHBOR_IP, hostname=hostname, **SNMP_ARGS) ] ids = [ i.value for i in snmp_walk(OID_NEIGHBOR_ID, hostname=hostname, **SNMP_ARGS) ] values = zip(ips, ids) return dict(zip(macs, values))
def updateToTable(ipList, db): listConn = {} for i in ipList: print i ip , community_string = i[0], i[1] print ip , community_string a = snmp_walk("BRIDGE-MIB:dot1dTpFdbTable", hostname=ip, community=community_string, version=2) listInter = {} for i in a: try: listInter[i.oid_index]={} except: pass # print i.value for i in a: if i.oid == "dot1dTpFdbAddress": listInter[i.oid_index][i.oid]= ':'.join(['%0.2x' % ord(x) for x in i.value ]) else: listInter[i.oid_index][i.oid]= i.value x = searchPortIdFromFdbPortandIp(listInter[i.oid_index]['dot1dTpFdbPort'], ip, db, community_string) y = searchPortIdFromMAC(listInter[i.oid_index]['dot1dTpFdbAddress'], db) if x == None or y == None: continue addNewTopoConnWith2portId(x,y, db) listConn[ip]=listInter # print listConn[ip] listConn = json.dumps(listConn,sort_keys=True, indent=4) print listConn
def bulk(self, oid): r = snmp_walk(oid, hostname=self.host, community=self.community_read, version=self.version) values = [(f'{oid}.{v.oid_index}', v.value) for v in r] return values
def walk_sector(self, sector, **options): try: for i in snmp_walk(OID_REG_TABLE, hostname=sector.fqdn(), **SNMP_ARGS): mac = extract_mac_from_oid(i.oid) if mac in known_macs: host = known_macs[mac] if options['show_matched']: self.stdout.write("%s on %s matched" % (host.fqdn(), sector)) old_location = (host.latitude, host.longitude) new_location = get_location(host.fqdn()) if all(new_location) and new_location != old_location: self.stdout.write("%s location changed from %s to %s" % ( host.fqdn(), ','.join(map(str, old_location)), ','.join(map(str, new_location)), )) if not options['dry_run']: host.latitude, host.longitude = new_location host.save() else: try: neighbors[sector.name] except KeyError: neighbors[sector.name] = get_neighbors(sector.fqdn()) neighbor = neighbors[sector.name].get(mac) self.stdout.write( "%s on %s not found in portal (neighbor discovery: %s)\n" % (mac, sector, str(neighbor or "disabled"))) if neighbor: new_host = Host() new_host.name = neighbor[1].replace('/', '-') new_host.type = "client" new_host.wlan_mac = mac new_host.latitude, new_host.longitude = get_location( neighbor[0]) if not options['dry_run']: new_host.save() try: ip = IPAddress.objects.get(ip=neighbor[0]) self.stdout.write( "Address was previously registered to %s." % str(ip)) except IPAddress.DoesNotExist: ip = IPAddress() ip.ip = neighbor[0] ip.host = new_host ip.interface = "wlan1" ip.primary = True if not options['dry_run']: ip.save() print "Added %s" % str(ip) else: if not options['dry_run']: self.stdout.write( "Cannot automatically add host record without neighbor discovery. " "Manual intervention required.") except EasySNMPTimeoutError as e: self.stderr.write("%s %s" % (e, sector.fqdn()))
def walk_sector(self, sector, **options): try: for i in snmp_walk(OID_REG_TABLE, hostname=sector.fqdn(), **SNMP_ARGS): mac = extract_mac_from_oid(i.oid) if mac in known_macs: host = known_macs[mac] if options['show_matched']: self.stdout.write("%s on %s matched" % (host.fqdn(), sector)) old_location = map(str, (host.latitude, host.longitude)) new_location = get_location(host.fqdn()) if all(new_location) and map(str, new_location) != old_location: self.stdout.write("%s location changed from %s to %s" % ( host.fqdn(), ','.join(old_location), ','.join(map(str, new_location)), )) if not options['dry_run']: host.latitude, host.longitude = new_location host.save() else: try: neighbors[sector.name] except KeyError: neighbors[sector.name] = get_neighbors(sector.fqdn()) neighbor = neighbors[sector.name].get(mac) self.stdout.write("%s on %s not found in portal (neighbor discovery: %s)\n" % (mac, sector, str(neighbor or "disabled"))) if neighbor: new_host = Host() new_host.name = slugify(unicode(neighbor[1])) new_host.type = "client" new_host.wlan_mac = mac new_host.latitude, new_host.longitude = get_location(neighbor[0]) if not options['dry_run']: try: new_host.save() except IntegrityError as e: self.stdout.write(str(e)) self.stdout.write("MAC changed. Manual review required to prevent DNS hijack.") continue try: ip = IPAddress.objects.get(ip=neighbor[0]) self.stdout.write("Address was previously registered to %s." % str(ip)) except IPAddress.DoesNotExist: ip = IPAddress() ip.ip = neighbor[0] ip.host = new_host ip.interface = "wlan1" ip.primary = True if not options['dry_run']: ip.save() print "Added %s" % str(ip) else: if not options['dry_run']: self.stdout.write("Cannot automatically add host record without neighbor discovery. " "Manual intervention required.") except (EasySNMPConnectionError, EasySNMPTimeoutError) as e: self.stderr.write("%s %s" % (e, sector.fqdn()))
def walk_SNMP_task(agente, oid): try: r_1 = (snmp_walk(oid, hostname=agente.Ip, community=agente.Comunidad, version=agente.Protocolo)) except Exception: r_1 = 'error' return r_1
def get_mac_on_port(self, port): """ Возвращает mac адрес с указанного порта :param port: Порт коммутатора, с которого необходимо получить мак адрес :return: MAC адрес or False (в случае если невозможно получить мак адрес с данного порта) """ current_function = 'Switch.Get_mac_on_port' mac_list = [] counter = 5 # Счетчик попыток взять мак адрес с порта while counter: counter -= 1 try: mac_addresses = snmp_walk('1.3.6.1.2.1.17.7.1.2.2.1.2', hostname=self.host, community='orion_comm', version=2) except exceptions.EasySNMPTimeoutError: self.log.error('Хост {} - недоступен'.format(self.host)) return False for octet in mac_addresses: # Ага согласно этому snmp oid'у значения у него это порт а сам оид состоит из мака # в десятичной системе счисления switch_port = octet.value if switch_port != str(port): continue # TODO протестить метод со свитчем без мака!!! # преобразуем строку oid'а вида iso.3.6.1.2.1.17.7.1.2.2.1.2.1998.40.59.130.1.246.64 # в список из 6 октетов в hex формат oid_line = octet.oid.split('.')[ -6:] # последние 6 значений списка это мак адрес for bit in oid_line: hex_mac = hex(int(bit)) hex_mac = hex_mac[2:] # удаляем лишнии символы if len(hex_mac) == 1: hex_mac = '0' + hex_mac mac_list.append(hex_mac.upper()) if len(mac_list) != 6: # бывает что свитч ен показывает мак с порта. т.к. с порта не идет никакой траффик и таблица # мак адресов очищается. Чтобы посмотреть мак с порта, необходимо порт выключить и включить заново self.port_disable(port) sleep(1) self.port_enable(port) sleep(10) continue if len(mac_list) == 6: mac = "{}-{}-{}-{}-{}-{}".format(*mac_list) return mac self.log.error('{}: Нет мак адреса у хоста {} с порта {}'.format( current_function, self.host, port)) return False
def get_cpu(device_list): # get current cpu utilization of all devices cpu_data = [] for host_ip in device_list: try: cpu = snmp_walk('.1.3.6.1.4.1.9.9.109.1.1.1.1.6', hostname=host_ip, community='public', version=2, use_sprint_value=True) for item in cpu: cpu_data.append(int(item.value)) except: cpu_data.append(-1) # value -1 indicates SNMP connection isn't properly established return cpu_data
def walk_ip(self, address: tuple, storage: Storage) -> list: if not self.snmp_enabled: return list() ip, port = address data = snmp_walk("1.3.6.1.4.1.40297.1.2.4", hostname=ip, community="hytera", version=1) repeater_info = storage.get_repeater_info_by_address(address) repeater_info.set_snmp_data(data) storage.set_repeater_info_by_address(address, repeater_info) return data
def retrieve_measurements(_oid): # Perform an SNMP walk return snmp_walk(oids=_oid, hostname=hostIP, community='public', version=1, timeout=3, retries=5, remote_port=161, use_long_names=True, retry_no_such=True, abort_on_nonexistent=True)
def updateToTable(db): cursor = db.cursor() exe = "SELECT deviceId, IP, community FROM device;" cursor.execute(exe) result = cursor.fetchall() for i in result: # print i a = snmp_walk("RFC1213-MIB::ipAdEntAddr", hostname=i[1], community=i[2], version=2) for j in a: if not checkDuplicate(i[0],j.value, db): exe = "INSERT INTO deviceIp (deviceId, ip) VALUES (%s, %s);" % (i[0], '\"'+j.value+'\"') cursor.execute(exe) db.commit()
def main(host_info: dict, community_strings: list = None) -> dict: """ Main easy-SNMP-walker runner :param community_strings: list of community strings to connect with (public, private, etc.) :param host_info: information about some host :return: nothing, empty dict """ # Define default community string if community_strings is None: community_strings = ["public", "private"] # Create directory for results SnmpWalkerDefaultValues.RESULTS_PATH.mkdir(exist_ok=True, parents=True) # Note: it is an important part that Nmap must detect open UDP # port 161 to scan it with SNMP-walker, or in another way, # you can modify this part with check somehow. if (host_info.get("nmap_scan", {}).get("udp", {}).get( "161", {}).get("state") != "open"): return {} host_ip, host_vendor, host_product = ( host_info.get("ip"), host_info.get("vendor"), host_info.get("product"), ) for community_string in community_strings: if is_host_scanned(host_ip, community_string, host_vendor, host_product): continue combined_results = [] try: walk_results = snmp_walk(hostname=host_ip, community="public", version=2) except Exception as unexp_e: print(f"Caught snmpwalk error: {str(unexp_e)}") return {} for walk_item in walk_results: combined_results.append({ "oid": walk_item.oid, "oid_index": walk_item.oid_index, "snmp_type": walk_item.snmp_type, "value": walk_item.value, }) save_results(combined_results, host_ip, community_string, host_vendor, host_product) return {}
def get(ip, community): # get arp table from an ip by SNMP data = snmp_walk("RFC1213-MIB::atPhysAddress", hostname=ip, community=community, version=2) # snmp walk to get data arp table from ip, return a list SNMP object listArp = {} # the dict store data arp for i in data: listArp['.'.join(i.oid_index.split('.')[2:])] = (':'.join( ['%0.2x' % ord(x) for x in i.value])) # the index of SNMP object has 4 last number is IP address, and the value is MAC address in OCTES STRING return listArp
def walk(oid, host, community, **kwargs): version = kwargs.get('version', 2) retries = kwargs.get('retries', 1) timeout = kwargs.get('timeout', 1) try: get = easysnmp.snmp_walk(oid, hostname=host, version=version, community=community, retries=retries, timeout=timeout) except: return if get: return _convertToDict(get)
def linkByArp(ip, community, db): a = snmp_walk("RFC1213-MIB::atPhysAddress", hostname=ip, community=community, version=2) deviceIps = getAllIpOfDeviceId(ip2deviceId(ip, db), db) # print deviceIps link = {} for i in a: temp_oid = i.oid_index.split('.') index = '.'.join(temp_oid[:2]) ipAt = '.'.join(temp_oid[2:]) try: link[index].append((ipAt, decodePhysAddress(i.value))) except: link[index] = [] link[index].append((ipAt, decodePhysAddress(i.value))) for i in link.values(): if len(i) == 2: addTopoWithLinkArp(i, db)
def check_printer(printer_name, base_oid): printer_snmp = snmp_walk(base_oid, hostname=printer_name, community=community, version=version) if not printer_snmp: print(" No Alerts") return for response in printer_snmp: if response.oid == "prtAlertSeverityLevel": selector = response.oid_index if response.value == "4": print(" WARNING: ({0})".format(printer_status(printer_snmp, selector))) elif response.value == "3": print(" CRITICAL: ({0})".format(printer_status(printer_snmp, selector))) elif response.value == "1": print(" OTHER: ({0})".format(printer_status(printer_snmp, selector))) return
def walk(self): dictresult = {} try: result = easysnmp.snmp_walk(self.oid, hostname=self.hostname, community=self.community, version=self.version) dictresult = { item.oid_index: { item.oid: (item.value, item.snmp_type) } for item in result } for item in result: oid = item.oid_index if oid == item.oid_index: dictresult[oid][item.oid] = (item.value, item.snmp_type) except: import sys print(sys.exc_info()) result = None return dictresult
def get_active_ports(self): """ Получает список всех активных портов коммутатора :return: Список активных портов """ # Включаем все порты: for port in range(1, 23): self.port_enable(port) sleep(5) try: port_status = snmp_walk('IF-MIB::ifOperStatus', hostname=self.host, community='orion_comm', version=2) except exceptions.EasySNMPTimeoutError: self.log.error('Хост {} - недоступен'.format(self.host)) return False else: active_ports = [] for port, line in enumerate(port_status): status = line.value switch_port = port + 1 # 24 порт у регистратора может быть приходом (транковым) if int(switch_port) < 24 and int(status) == 1: active_ports.append(switch_port) # Отключаем все порты: for port in range(1, 23): self.port_disable(port) sleep(5) if not active_ports: return False return active_ports
def updateToTable(ipList, db): listConn = {} for i in ipList: ip, community = i[0], i[1] a = snmp_walk("BRIDGE-MIB:dot1dTpFdbTable", hostname=ip, community=community, version=2) # a = snmp_walk("BRIDGE-MIB:dot1dTpFdbAddress", hostname=ip, community='BKCS', version=2) listInter = {} if len(a) == 0: ### The device cannot get brigde-mib linkByArp(ip, community, db) continue for i in a: try: listInter[i.oid_index]={} except: pass for i in a: # print i if i.oid == "dot1dTpFdbAddress": listInter[i.oid_index][i.oid]= ':'.join(['%0.2x' % ord(x) for x in i.value ]) else: listInter[i.oid_index][i.oid]= i.value x = searchportIdFromFdbPortandIp(listInter[i.oid_index]['dot1dTpFdbPort'], ip, db, community) y = searchportIdFromMAC(listInter[i.oid_index][u'dot1dTpFdbAddress'], db) print x, y, ip if x != False : if y != False: addNewTopoConnWith2portId(x,y, db) else: addNewTopoConnWithMac(x, listInter[i.oid_index][u'dot1dTpFdbAddress'], db) listConn[ip]=listInter
from easysnmp import Session, snmp_get, snmp_walk ss = snmp_get('1.3.6.1.2.1.2.2.1.2.1', hostname='192.168.122.60', community='snmpPassword', version=2) print(ss) ss = snmp_get('1.3.6.1.2.1.1.5.0', hostname='192.168.122.60', community='snmpPassword', version=2) print(ss) ss = snmp_walk('1.3.6.1.2.1.2.2.1.8', hostname='192.168.122.60', community='snmpPassword', version=2) for i in ss: print(i)
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)
rows = queryDB("SELECT * FROM probes", []) for row in rows: result = "Probe request succeeded." if row[2] == 0: # ICMP check response = os.system("ping -c 1 -w2 {} > {} 2>&1".format(row[1], dummyfile)) with open(dummyfile, 'r') as fd: result = "ICMP ping reply:\n\n{}".format(fd.read()) elif row[2] == 161: # SNMP check from easysnmp import snmp_walk try: url = row[1] community = "public" if "/" in row[1]: url = row[1].split('/')[0] community = row[1].split('/')[1] data = snmp_walk("system", hostname=url, community=community, version=1) result = "SNMP walk reply:\n\n" for item in data: result += "{}.{}: {}\n".format(item.oid, item.oid_index, item.value) response = 0 except Exception as e: result = "SNMP request failed:\n\n{}".format(e) response = 1 elif row[2] == 80 or row[2] == 443: # HTTP check try: if row[1][:4] != 'http': if row[2] == 80: url = "http://{}/".format(row[1]) else: url = "https://{}/".format(row[1]) else:
version=2) result = '%s.%s.raw_system_cpu_time.%s %s %d\n' % ( roxie_name, server.replace('.', '_').replace( '\n', ''), 'count', get_raw_idle_cpu_time.value, time.time()) get_raw_nice_cpu_time = easysnmp.snmp_get(raw_nice_cpu_time, hostname=server, community='public', version=2) result = '%s.%s.raw_nice_cpu_time.%s %s %d\n' % ( roxie_name, server.replace('.', '_').replace( '\n', ''), 'count', get_raw_nice_cpu_time.value, time.time()) sender.sendall(result) get_total_cpu_count = easysnmp.snmp_walk(total_cpu_count, hostname=server, community='public', version=2) result = '%s.%s.total_cpu_count.%s %s %d\n' % ( roxie_name, server.replace('.', '_').replace( '\n', ''), 'count', len(get_total_cpu_count), time.time()) sender.sendall(result) get_total_swap_size = easysnmp.snmp_get(total_swap_size, hostname=server, community='public', version=2) result = '%s.%s.total_swap_size.%s %s %d\n' % ( roxie_name, server.replace('.', '_').replace( '\n', ''), 'count', get_total_swap_size.value, time.time()) sender.sendall(result)
from easysnmp import snmp_get, snmp_set, snmp_walk # Perform an SNMP walk system_items = snmp_walk(u'.1.3.6.1.2.1', hostname='128.153.145.20', community='cacti', version=1) # Each returned item can be used normally as its related type (str or int) # but also has several extended attributes with SNMP-specific information for item in system_items: print ('{oid}.{oid_index} {snmp_type} = {value}'.format( oid=item.oid, oid_index=item.oid_index, snmp_type=item.snmp_type, value=item.value ))
from easysnmp import snmp_get, snmp_set, snmp_walk # Grab a single piece of information using an SNMP GET snmp_get('sysDescr.0', hostname='192.168.0.100', community='public', version=1) # Perform an SNMP SET to update data snmp_set( 'sysLocation.0', 'My Cool Place', hostname='localhost', community='public', version=1 ) # Perform an SNMP walk snmp_walk('system', hostname='localhost', community='public', version=1)
#!/usr/bin/env python3 # # Brandon Parncutt # [email protected] # # snmpd_df.py import easysnmp import re import optparse storage_table = easysnmp.snmp_walk([ 'hrStorageDescr', 'hrStorageSize', 'hrStorageUsed', 'hrStorageAllocationUnits' ], hostname='localhost', community='public', version=2) disk_index = {item.oid_index: {item.oid: item.value} for item in storage_table} for item in storage_table: oid = item.oid_index if oid == item.oid_index: disk_index[oid][item.oid] = item.value mem_match = re.compile('.*[Mm]emory') badkeys = [ key for key in disk_index.keys() if re.match(mem_match, disk_index[key]['hrStorageDescr'])
def snmp_walk(*oids, **sessargs): """snmp walk a host for an oid""" if not oids: oids = ['.1.3.6.1.2.1'] sessargs = {**default_snmp, **sessargs} return easysnmp.snmp_walk(*oids, **sessargs)