def main(): opts = parseArgs() pyt = pytricia.PyTricia() pyt.insert('0.0.0.0/0', "root") pyt.insert('10.0.0.0/8', "RFC1918 root") pyt.insert('172.12.0.0/12', "RFC1918 root") pyt.insert('192.168.0.0/16', "RFC1918 root") prefx = {} IGNORED_INTERFACE = [ 'bme0' , 'bme0.32768', 'lo' ] for device in opts['hosts']: try: session = Session(hostname=device, community=opts['community'], version=2) ipent = session.walk('IP-MIB::ipAdEntAddr') for item in ipent: ip = item.value ifIndex = session.get('IP-MIB::ipAdEntIfIndex.' + ip) mask = session.get('IP-MIB::ipAdEntNetMask.' + ip) ifName = session.get('IF-MIB::ifName.' + ifIndex.value) if ifName in IGNORED_INTERFACE: print("Skipping %s" % ifName) continue prefix = ip + "/" + str(IPNetwork('0.0.0.0/' + mask.value ).prefixlen) pref = IPNetwork(prefix) pyt.insert(str(prefix), device + "_" + ifName.value) except Exception, err: print("\tTIMEOUT: " +fw) print("\t" + str(err)) continue
def get_interface_stats(task, interface_dict): f = open(f'{task.host.hostname}_interface_{interface_dict["ifslug"]}.txt', 'a') # session = Session(hostname=task.host.hostname, community='private', version=2) session = Session( hostname=task.host.hostname, version=3, security_level='auth_with_privacy', security_username='******', auth_protocol='SHA', auth_password='******', privacy_password='******', privacy_protocol='AES', ) in_octets = session.get( f'.1.3.6.1.2.1.2.2.1.10.{interface_dict["ifindex"]}') out_octets = session.get( f'.1.3.6.1.2.1.2.2.1.16.{interface_dict["ifindex"]}') print(in_octets, out_octets) #Printing data just to make sure that it's running... f.write( f'{datetime.now().isoformat()},{interface_dict["ifname"]},{in_octets.value},{out_octets.value}\n' ) f.close() return [in_octets, out_octets]
def main(): parser = argparse.ArgumentParser(description=description) parser.add_argument("-H", "--hostname", help="IP Address / Hostname to check [REQUIRED]",type=str, required=True) parser.add_argument("-c", "--community",help="SNMP Community (default 'public')",type=str,default='public') args = parser.parse_args() hostname = args.hostname comm = args.community session = Session(hostname=hostname, community=comm, version=2) try: item = session.walk(ifName) except: sys.exit('\nSNMP PROBLEM host '+hostname+" check IP and COMMUNITY\n") # get uptime to calculate last change uptime = session.get(sysUpTime).value print '\nHOST\t'+hostname print "\nUPTIME\t"+str(timedelta(seconds=(int(uptime)/100)))+"\n" # port names to include or ignore to filter useless values include= ('ethernet') ignore = ('Vl','vlan','VLAN','VLAN-','Trk','lo','oobm','Po','Nu','Gi/--Uncontrolled','Gi/--Controlled','Te/--Uncontrolled','Te/--Controlled') for value in item: # remove all digits from port names before filtering result = ''.join(i for i in value.value if not i.isdigit()) if (result in include) or (result not in ignore): ifname = value.value # id defines the interface, will be appended to following snmp get id = value.oid_index #descr = session.get(ifAlias+id) opstatus = ifstatus[session.get(ifOperStatus+'.'+id).value] lastchangedate = lastchange2date(uptime,session.get(ifLastChange+'.'+id).value) print str(ifname)+"\tSTATUS "+opstatus+"\tLAST CHANGE SINCE DAYS\t"+lastchangedate
def get_memory_snmp(self): session = Session(hostname=str(self.device["ip_mgmt"]), community=self.device["snmp"]["community"], version=self.device["snmp"]["version"]) try: mem_util_used = session.get( invent.get_oid("mem_util_used", self.device["vendor"])).value mem_util_used = int(mem_util_used) if self.device["vendor"] == "Cisco": mem_util_free = session.get( invent.get_oid("mem_util_free", self.device["vendor"])).value mem_util_used = (mem_util_used * 100) / (mem_util_used + int(mem_util_free)) mem_util_free = 100 - mem_util_used elif self.device["vendor"] == "Juniper": mem_util_free = 100 - mem_util_used self.logger.info( "Finished collecting Memory utilization for device {:s}". format(self.device["ip_mgmt"])) except: mem_util_used = None mem_util_free = None self.logger.warning( "Error collecting Memory utilization for device {:s}".format( self.device["ip_mgmt"])) # TODO: tobe delete, only for demo import random mem_util_used = random.randint(10, 50) mem_util_free = 100 - mem_util_used return mem_util_used, mem_util_free
class SNMP_Service(): def __init__(self, hostname, **kwargs): self.switch = hostname self.version = kwargs.get('version', 2) if self.version < 3: self.community = kwargs.get('community', 'public') self.session = Session(hostname=self.switch, community=self.community, version=self.version) else: self.security_level = kwargs.get('security_level', 'authNoPriv') self.security_username = kwargs.get('security_username', 'opro') self.auth_protocol = kwargs.get('auth_protocol', 'SHA') self.auth_password = kwargs.get('auth_password', '') self.privacy_protocol = kwargs.get('privacy_protocol', 'aes') self.privacy_password = kwargs.get('privacy_password', '') self.session = Session(hostname=self.switch, security_level=self.security_level, security_username=self.security_username, auth_protocol=self.auth_protocol, auth_password=self.auth_password, privacy_protocol=self.privacy_protocol, privacy_password=self.privacy_password, version=self.version) def sys_descr(self): d = self.session.get('sysDescr.0') [descr, fw, rom] = d.value.split(',') return (self.switch, descr, fw, rom) def num_ports(self): d = self.session.get('') [descr, fw, rom] = d.value.split(',') def model(self): d = self.session.get('ENTITY-MIB::entPhysicalModelName.1') return d def firmware(self): d = self.session.get('ENTITY-MIB::entPhysicalSoftwareRev.1') return d def get(self, oid): return self.session.get(oid) def getfirst(self, oid): ret = self.session.get_next(oid) while ret is not None and not len(ret.value): ret = self.session.get_next(ret.oid) return ret def getall(self, oid, filter_by_value=False): ret = self.session.walk(oid) if filter_by_value: return [lambda x: x.value for x in ret] return ret def set(self, oid, value, snmp_type=None): return self.session.set(oid, value, snmp_type) def set_multiple(self, oids): return self.session.set_multiple(oids)
def main(): opts = parseArgs() pyt = pytricia.PyTricia() pyt.insert('0.0.0.0/0', "root") pyt.insert('10.0.0.0/8', "RFC1918 root") pyt.insert('172.12.0.0/12', "RFC1918 root") pyt.insert('192.168.0.0/16', "RFC1918 root") prefx = {} IGNORED_INTERFACE = ['bme0', 'bme0.32768', 'lo'] for device in opts['hosts']: try: session = Session(hostname=device, community=opts['community'], version=2) ipent = session.walk('IP-MIB::ipAdEntAddr') for item in ipent: ip = item.value ifIndex = session.get('IP-MIB::ipAdEntIfIndex.' + ip) mask = session.get('IP-MIB::ipAdEntNetMask.' + ip) ifName = session.get('IF-MIB::ifName.' + ifIndex.value) if ifName in IGNORED_INTERFACE: print("Skipping %s" % ifName) continue prefix = ip + "/" + str( IPNetwork('0.0.0.0/' + mask.value).prefixlen) pref = IPNetwork(prefix) pyt.insert(str(prefix), device + "_" + ifName.value) except Exception, err: print("\tTIMEOUT: " + fw) print("\t" + str(err)) continue
def snmpConnection(version, community, hostname): try: session = Session(hostname=hostname, community=community, version=version) print(session) except EasySNMPConnectionError: print("ERROR: Invalid hostname or community.") exit(1) try: info = session.get('iso.3.6.1.2.1.1.5.0') print("\nName: ", info.value) info = session.get('iso.3.6.1.2.1.1.6.0') print("Location: ", info.value) info = session.get('iso.3.6.1.2.1.1.1.0') print("Description: ", info.value) info = session.get('iso.3.6.1.2.1.1.2.0') print("ID: ", info.value) info = session.get('iso.3.6.1.2.1.1.4.0') print("Contact: ", info.value) except: print("\nSystem info aren't available") return session
class OpticTransceiver: def __init__(self, node, port): self.node = node self.port = port self.fqdn = node + config['domain'] self.session = self.get_session() self.port_index = self.get_port_index() def get_session(self): self.session = Session(hostname=self.fqdn, community=config['snmp_community'], version=2) return self.session def get_port_index(self): port_number = self.port.split('/')[-1] rx_tag = ' ' + port_number + ' Rx' receive_tag = '/' + port_number + ' Receive' rx_tags = [rx_tag, receive_tag] # walk entity-mib walk = self.session.walk(config['entity_mib']) # filter entity-mib for port index for snmpvar in walk: if any(tag in snmpvar.value for tag in rx_tags): port_oid = snmpvar.oid port_index = port_oid.split('.')[-1] return port_index def poll_light_lvl(self): port_lvl_oid = config['light_lvl_mib'] + self.port_index get = self.session.get(port_lvl_oid) light_lvl = float(get.value) / 10 return(light_lvl) def poll_low_warn_threshold(self): port_threshold_oid = config['light_threshold_mib'] + self.port_index + '.' low_warn_oid = port_threshold_oid + '3' get = self.session.get(low_warn_oid) low_warn = float(get.value) / 10 return(low_warn) def poll_thresholds(self): port_threshold_oid = config['light_threshold_mib'] + self.port_index + '.' high_warn_oid = port_threshold_oid + '1' high_alarm_oid = port_threshold_oid + '2' low_warn_oid = port_threshold_oid + '3' low_alarm_oid = port_threshold_oid + '4' get = self.session.get(low_warn_oid) low_warn = float(get.value) / 10 return(low_warn)
def executa_snmp(ip): session = Session(hostname=ip, community='public', version=2) # You may retrieve an individual OID using an SNMP GET #location = session.get('sysLocation.0') # You may also specify the OID as a tuple (name, index) # Note: the index is specified as a string as it can be of other types than # just a regular integer #contact = session.get(('sysContact', '0')) # And of course, you may use the numeric OID too #description = session.get('.1.3.6.1.2.1.1.1.0') # Set a variable using an SNMP SET #session.set('sysLocation.0', 'The SNMP Lab') # Perform an SNMP walk #testes #teste = session.get('.1.3.6.1.4.1.2021.11.9.0') #teste = session.get('.1.3.6.1.4.1.2021.11.10.0') #teste = session.get('.1.3.6.1.4.1.2021.10.1.3.1') #teste = session.get('.1.3.6.1.4.1.9.9.109.1.1.1.1.5.1') #teste = session.get('.1.3.6.1.4.1.2021.11.50.0') porc_proc = session.get( '.1.3.6.1.4.1.2021.11.11.0') #processador ocioso porcentagem total_mem = session.get('.1.3.6.1.4.1.2021.4.5.0') #total de memoria uso_mem = session.get('.1.3.6.1.4.1.2021.4.6.0') #ram usada porc_disco = session.get( '1.3.6.1.4.1.2021.9.1.9.1') #porcentagem uso disco info = {} info["porc_proc"] = porc_proc.value info["total_mem"] = total_mem.value info["uso_mem"] = uso_mem.value info["porc_disco"] = porc_disco.value '''nome_interfaces = session.walk('ifName') entr_interfaces = session.walk('ifInOctets') said_interfaces = session.walk('ifOutOctets') interfaces = {} interfaces[ip] = {} interfaces[ip]["memory"] = teste # Each returned item can be used normally as its related type (str or int) # but also has several extended attributes with SNMP-specific information #print(entr_interfaces) c = 0 for item in nome_interfaces: interfaces[ip][str(c)] = {} interfaces[ip][str(c)]["index"] = str(c) interfaces[ip][str(c)]["snmp-id"] = item.oid interfaces[ip][str(c)]["name"] = item.value interfaces[ip][str(c)]["pktin"] = entr_interfaces[c].value interfaces[ip][str(c)]["pktout"] = said_interfaces[c].value c += 1 return interfaces ''' return info
def get_model_sw(a3_arg): session_a3_1 = Session(hostname=a3_arg, community='ntcore', version=2) oid_descr = session_a3_1.get('.1.3.6.1.2.1.1.1.0') model_sw_1 = str(u'{value}'.format(value=oid_descr.value)) session_a3_2 = Session(hostname=cfg_ini['A3'][a3_arg], community='ntcore', version=2) oid_descr1 = session_a3_2.get('.1.3.6.1.2.1.1.1.0') model_sw_2 = str(u'{value}'.format(value=oid_descr1.value)) return (model_sw_1,model_sw_2)
def getInterfaces(ipRouter, rname=None): global network session = Session(hostname=ipRouter, community=COMMUNITY, version=2) router = network.getRouter(rname) ipslist = (session.walk('RFC1213-MIB::ipAdEntAddr')) for ip in ipslist: index = (session.get('RFC1213-MIB::ipAdEntIfIndex.' + ip.value)) name = (session.get('IF-MIB::ifDescr.' + index.value)) mask = (session.get('RFC1213-MIB::ipAdEntNetMask.' + ip.value)) speed = (session.get('IF-MIB::ifSpeed.' + index.value)) cost = (session.get('OSPF-MIB::ospfIfMetricValue.' + ip.value))
def get_system_status(self): session = Session(hostname=str(self.device["ip_mgmt"]), community=self.device["snmp"]["community"], version=self.device["snmp"]["version"]) timestamp = datetime.now() try: # print self.device["ip_mgmt"] cpu_util = session.get( invent.get_oid("cpu_util", self.device["vendor"])).value mem_util_used = session.get( invent.get_oid("mem_util_used", self.device["vendor"])).value mem_util_free = session.get( invent.get_oid("mem_util_free", self.device["vendor"])).value uptime = session.get( invent.get_oid("uptime", self.device["vendor"])).value uptime_date = (datetime.now() - timedelta( seconds=int(uptime) / 100)).strftime('%A, %d-%m-%Y, %H:%M:%S') mem_util_used = int(mem_util_used) #Normalization mempry in Percentation if self.device["vendor"] == "Cisco": mem_util_used = (mem_util_used * 100) / (mem_util_used + int(mem_util_free)) mem_util_free = 100 - mem_util_used if self.device["vendor"] == "Juniper": mem_util_free = 100 - int(mem_util_used) system_status_dict = { "hostname": self.device["hostname"], "vendor": self.device["vendor"], "cpu": cpu_util, "mem_used": mem_util_used, "mem_free": mem_util_free, "uptime": uptime_date, "timestamp": timestamp } self.logger.info( "Finished collecting device utilization for device {:s}". format(self.device["hostname"])) except: self.logger.warning( "Error collecting device utilization for device {:s}".format( self.device["hostname"])) system_status_dict = { "hostname": self.device["hostname"], "vendor": self.device["vendor"], "cpu": "N/A", "mem_used": "N/A", "mem_free": "N/A", "uptime": "N/A", "timestamp": timestamp } return system_status_dict
def interfaces_stats(request): machine_list = Machines.objects.all() all_interfaces = Interfaces.objects.all().order_by('m_id', 'snmp_number') response = {} i = 0 # Checking for all known interfacs on all hosts for interface in all_interfaces: in_oid = '.1.3.6.1.2.1.2.2.1.10.' + str(interface.snmp_number) out_oid = '.1.3.6.1.2.1.2.2.1.16.' + str(interface.snmp_number) # Get ip address and credentials from DB machine = Machines.objects.get(pk=interface.m_id) ip = machine.ip_address community = machine.community_name try: session = Session(hostname=ip, community=community, version=2) counter_in = session.get(in_oid).value counter_out = session.get(out_oid).value stat = Stats( i_id=interface.id, counter_in=counter_in, counter_out=counter_out, timestamp=datetime.now().strftime('%Y-%m-%d %H:%M:%S')) stat.save() response[i] = { 'ip': ip, 'interface': interface.name, 'counter_in': counter_in, 'counter_out': counter_out, 'status': 'OK' } i += 1 except (IntegrityError, ValueError, EasySNMPTimeoutError) as error: response[i] = { 'ip': ip, 'interface': interface.name, 'counter_in': counter_in, 'counter_out': counter_out, 'status': error } i += 1 return render(request, 'facer/interfaces_stats.html', { 'machine_list': machine_list, 'response': response })
def get_tot_mem(chat_id, bot): """ Send response of 'snmpget' request for memTotalReal (Total RAM) :param chat_id: chat id to send SNMP get response. :param bot: bot instance. """ try: session = Session(hostname=host_details.get_host(), community=host_details.get_community(), version=host_details.get_version()) memTotalReal = session.get(".1.3.6.1.4.1.2021.4.5.0") mem = int(memTotalReal.value) bot.sendMessage( chat_id, 'Total RAM memory of the host: ' + host_details.get_host() + ' = ' + str(mem) + "kB") bot.sendMessage(chat_id, 'Back to command list', reply_markup=bot_command.keyboard) except exce.EasySNMPError as error: bot.sendMessage( chat_id, 'Error during processing the request, agent: <' + host_details.get_host() + ' ' + host_details.get_community() + '> on tot mem request') bot_command.back_home(chat_id, bot) print(error)
def determine_printer_model(hostname, version): """ Get the printer's model name from the SNMP data. The function tries to get the printer's model name through the SNMP data. It can sometimes raise a SystemError exception but I have seen it be multiple different errors so it returns -2 indicating that it is an unexpected error. If the model name is actually a string of 'NOSUCHINSTANCE', that means that the printer is too old and/or it needs a firmware update to have all the SNMP access. Args: hostname (str): version (int): Returns: printer_model_name (str): A string with the printer's models name retrieved from SNMP. Negative int: -2 = unspecified error. -3 = SNMP data not given (printer/firmware too old). """ session = Session(hostname=hostname, community='public', version=version) try: printer_model_name = session.get('.1.3.6.1.2.1.25.3.2.1.3.1').value except SystemError: return -2 # If the SNMP data gives 'NOSUCHINSTANCE' that means that the firmware of # the printer needs to be updated or the printer is too old. if str(printer_model_name) == "NOSUCHINSTANCE": return -3 return printer_model_name
def verificaSenha(self): usuario = self.nome.get() senha = self.senha.get() ip = self.ip.get() hash = self.hash.get() encryption = self.encryption.get() try: global session global numInterfaces session = Session(hostname=ip, version=3, security_level='auth_with_privacy', security_username=usuario, auth_protocol=hash, auth_password=senha, privacy_protocol=encryption, privacy_password=senha) numInterfaces = int(session.get('ifNumber.0').value) self.mensagem["text"] = "Autenticado" t = threading.Thread(target=analyze_interfaces) t.start() ani = animation.FuncAnimation(fig, plot_chart, interval=1000) ani2 = animation.FuncAnimation(fig2, plot_chart2, interval=1000) ani3 = animation.FuncAnimation(fig3, plot_chart3, interval=1000) plt.show() except: print('Ocorreu um erro. Verifique o que aconteceu.') self.mensagem["text"] = "Falha durante autenticacao"
def get_usage_mem(chat_id, bot): """ Send response of 'snmpget' request for usage RAM. :param chat_id: chat id to send SNMP get response. :param bot: bot instance. """ try: session = Session(hostname=host_details.get_host(), community=host_details.get_community(), version=host_details.get_version()) mem_avail_real = session.get(".1.3.6.1.4.1.2021.4.6.0") mem_total_real = session.get(".1.3.6.1.4.1.2021.4.5.0") mem_usage = float(mem_total_real.value) - float(mem_avail_real.value) percentage = (100 * mem_usage) / float(mem_total_real.value) gb_usage = mem_usage / (1024 * 1024) bot.sendMessage( chat_id, 'RAM usage on: ' + host_details.get_host() + ' = ' + str(round(percentage, 2)) + "%" + " (" + str(round(gb_usage, 2)) + "GB)") bot.sendMessage(chat_id, 'Back to command list', reply_markup=bot_command.keyboard) except exce.EasySNMPError as error: bot.sendMessage( chat_id, 'Error during processing the request, agent: <' + host_details.get_host() + ' ' + host_details.get_community() + '> on used mem request') bot_command.back_home(chat_id, bot) print(error)
def click_entrar(): endereco = textentryEndereco.get() usuario = textentryUsuario.get() senha = textentrySenha.get() try: global session #session = Session(hostname=endereco, community='public', version=2, use_sprint_value = True) session = Session(hostname=endereco, version=3, security_level="auth_with_privacy", security_username=usuario, auth_protocol=str(tipoAuth.get()), auth_password=senha,privacy_protocol=str(tipoCript.get()), privacy_password=senha, use_sprint_value = True) print(str(tipoAuth.get())) print(str(tipoCript.get())) textEndereco.insert(END, endereco) textEndereco.config(state=DISABLED) name = session.get('sysName.0').value textName.insert(END, name) textName.config(state=DISABLED) updateTime() updateBytes() checkSites() labelErro.config(text="") textentryEndereco.delete(0, END) textentryUsuario.delete(0, END) textentrySenha.delete(0, END) windowPrincipal.tkraise() except: labelErro.config(text="Não foi possível abrir a sessão!")
def get_tasks(chat_id, bot): """ Send number of tasks in execution on host :param chat_id: chat id to send response. :param bot: bot instance. """ try: session = Session(hostname=host_details.get_host(), community=host_details.get_community(), version=host_details.get_version()) numTasks = session.get(".1.3.6.1.2.1.25.1.6.0") num = int(numTasks.value) bot.sendMessage( chat_id, 'Actual tasks in execution on: ' + host_details.get_host() + ' = ' + str(num)) bot.sendMessage(chat_id, 'Back to command list', reply_markup=bot_command.keyboard) except exce.EasySNMPError as error: bot.sendMessage( chat_id, 'Error during processing the request, agent: <' + host_details.get_host() + ' ' + host_details.get_community() + '> on num tasks request') bot_command.back_home(chat_id, bot) print(error)
def discover(subnet): """ Function that discovers the devices in the subnet by doing SNMP get on the system description OID. Subnet obtained from system argument :param subnet: IPNetwork object :return: None """ global file_open global next_ip # Running through al the hosts in the subnet for ip in subnet: if next_ip and ip < next_ip: continue session = Session(hostname=ip.exploded, community=sys.argv[2], version=2, retries=1) try: sysdescription = session.get('1.3.6.1.2.1.1.1.0') if re.search('JUNOS ([^ ]+)', sysdescription.value): logging.info("Found Juniper at %s" % (ip.exploded, )) with open(sys.argv[3], 'a') as f: f.write(ip.exploded + ':juniper:up\n') else: logging.info("Skipping %s: Not Junos" % (ip.exploded, )) except Exception as e: logging.info('Skipping: %s: %s' % (ip.exploded, str(e)))
class SNMPManager(): _session_ = None _snmp_host_ = None def __init__(self, snmp_host, community, version): self._snmp_host_ = snmp_host self._session_ = Session(hostname=snmp_host, community=community, version=version, use_long_names=True, use_sprint_value=True) def is_alive(self): try: val = self._session_.get('SNMPv2-MIB::sysName.0') if val.value: return True except: snmp_logger.error("Unable to reach snmp host %s" % self._snmp_host_, exc_info=True) pass return False def walk_oid(self, oid_name): try: return self._session_.walk(oid_name) except EasySNMPTimeoutError as timeout: snmp_logger.error("SNMP Timeout Error,", exc_info=True) snmp_logger.info("No values will be collected") return []
def handle(self, *args: Any, **options: Any): devs = (Device.objects.exclude( ip_address=None, man_passw=None, ).filter(dev_type__in=[1, 9, 10]).iterator()) for dev in devs: try: print("Try to scan", str(dev)) ses = Session(str(dev.ip_address), 2, str(dev.man_passw or "public")) sys_name = ses.get(".1.3.6.1.2.1.1.1.0").value if not sys_name or sys_name == "NOSUCHINSTANCE": continue if "DGS-1100-10" in sys_name: dev.dev_type = 1 elif "DGS-1100-06" in sys_name: dev.dev_type = 10 elif "DGS-3120-24SC" in sys_name: dev.dev_type = 9 else: continue print("\tSet dev type to:", sys_name) dev.save(update_fields=["dev_type"]) except (EasySNMPError, SystemError) as err: print(str(dev), "ERROR:", err)
def estatusInterfaces(hostname, community, version, num): session = Session(hostname=hostname, community=community, version=version) try: description = str(session.get('1.3.6.1.2.1.2.2.1.8.' + str(num))) except EasySNMPTimeoutError: description = 'Timeout Error' return obtenerSubcadena(description)
def get_power(): session = Session(hostname=pdu_ip, community='perccom', version=2) sum = 0 for i in range(1,9): snmp_response = session.get('1.3.6.1.4.1.13742.6.5.4.3.1.4.1.' + str(i) + ".5") sum += int(snmp_response.value) return sum
class Reader(object): def __init__(self, host, port=161, community='public', version=2, timeout=60): self._host = host self._port = port self._community = community self._version = version self._timeout = timeout def __enter__(self): # Create an SNMP session to be used for all our requests self._session = Session(hostname=self._host, remote_port=self._port, timeout=self._timeout, community=self._community, version=self._version) return self def __exit__(self, type, value, traceback): pass def read(self, oid, **kwargs): snmpval = self._session.get(oid) val = snmpval.value return val
def get_cpu_usage(chat_id, bot): """ Send response of 'snmpget' request for CPU usage. :param chat_id: chat id to send SNMP get response. :param bot: bot instance. """ try: session = Session(hostname=host_details.get_host(), community=host_details.get_community(), version=host_details.get_version()) cpuUsage = session.get(".1.3.6.1.4.1.2021.11.9.0") cpu = int(cpuUsage.value) bot.sendMessage( chat_id, 'Actual CPU percentage: ' + host_details.get_host() + ' = ' + str(cpu) + "%") bot.sendMessage(chat_id, 'Back to command list', reply_markup=bot_command.keyboard) except exce.EasySNMPError as error: bot.sendMessage( chat_id, 'Error during interrogation, agent: <' + host_details.get_host() + ' ' + host_details.get_community() + '> on cpu request') bot_command.back_home(chat_id, bot) print(error)
def getSNMP(self): # Get data from the host via SNMP session = Session(hostname=self.IP, community=config['auth']['SNMPCommunity'], version=1) location = session.get('sysLocation.0') # Converts the address string into a coordinate pair self.coords = Geocoder.geocode(location)[0].coordinates
def get_disk(chat_id, bot): """ Send response of 'snmpget' request for dskPercent (Disk usage percent) :param chat_id: chat id to send SNMP get response. :param bot: bot instance. """ try: session = Session(hostname=host_details.get_host(), community=host_details.get_community(), version=host_details.get_version()) disk = session.get(".1.3.6.1.4.1.2021.9.1.9.1") bot.sendMessage( chat_id, 'Actual Disk usage on: ' + host_details.get_host() + ' = ' + str(disk.value) + "%") bot.sendMessage(chat_id, 'Back to command list', reply_markup=bot_command.keyboard) except exce.EasySNMPError as error: bot.sendMessage( chat_id, 'Error during processing the request, agent: <' + host_details.get_host() + ' ' + host_details.get_community() + '> on disk request') bot_command.back_home(chat_id, bot) print(error)
def get_vendor(ip_add, snmp_community): session = Session(hostname=ip_add, community=snmp_community, version=2) vendor = session.get('iso.3.6.1.2.1.1.1.0') if "isco" in vendor.value: return "Cisco" elif "niper" in vendor.value: return "Juniper"
def connect(): # Create an SNMP session to be used for all our requests session = Session(hostname=HOST_NAME, community='public', version=2) # You may retrieve an individual OID using an SNMP GET location = session.get('sysLocation.0') return session
def polling_routers(ipRouter): session = Session(hostname=ipRouter, community=COMMUNITY, version=2) name = (session.get('SNMPv2-MIB::sysName.0')) router = network.getRouter(name.value) if router is None: router = Router(name.value) print router.getName()
def snmpGetWrapper(self, oids): try: session = Session(hostname= self.pp.get_cmip, community="public", version=2, timeout=1, retries=1, ) return session.get(oids) except Exception as xcp: print(xcp) # print traceback.print_exc() return {'error': 1, 'msg': str(xcp)}
def _poll_oid(self, host, oid): try: session = Session(hostname=host, community='clearwater', version=2) return session.get(oid).value except exceptions.EasySNMPTimeoutError: cluster_logger.warning( "SNMP request timeout. Unable to access '%s'", host) return None
def get_traffic(): session = Session(hostname=switch_ip, community='perccom', version=2) # variable to hold SNMP return values inOctets = 0 outOctets = 0 # Loop to get the necessary SNMP-GET queries for i in range(1,25): if i < 10: bytes_in = session.get('1.3.6.1.2.1.2.2.1.10.1010' + str(i)) bytes_out = session.get('1.3.6.1.2.1.2.2.1.16.1010' + str(i)) else: bytes_in = session.get('1.3.6.1.2.1.2.2.1.10.101' + str(i)) bytes_out = session.get('1.3.6.1.2.1.2.2.1.16.101' + str(i)) inOctets += int(bytes_in.value) outOctets += int(bytes_out.value) # RETURN IN + OUT BYTES return inOctets + outOctets
def main(): parser = argparse.ArgumentParser() parser.add_argument("-H", "--hostname", help="IP Address / Hostname to check [REQUIRED]",type=str, required=True) parser.add_argument("-c", "--community",help="SNMP Community (default 'public')",type=str,default='public') parser.add_argument("-d", "--down",help="Show only down interfaces (default n)",type=str,choices=['y', 'n'],default='n') # port names to include or ignore to filter useless values include= ('ethernet') ignore = ('StackSub-St-','StackPort','Vl','vlan','VLAN','VLAN-','Trk','lo','oobm','Po','Nu','Gi/--Uncontrolled','Gi/--Controlled','Te/--Uncontrolled','Te/--Controlled') args = parser.parse_args() hostname = args.hostname session = Session(hostname=hostname, community=args.community, version=2) try: item = session.walk(ifName) except: sys.exit('\nSNMP CONNECTION PROBLEM host '+hostname+" check IP and COMMUNITY\n") # get uptime to calculate last change uptime = session.get(sysUpTime).value print('\nHOST\t {}'.format(hostname)) print("\nDEVICE UPTIME\t {}\n".format(str(timedelta(seconds=(int(uptime)/100))))) for value in item: # remove all digits from port names before filtering result = ''.join(i for i in value.value if not i.isdigit()) if (result in include) or (result not in ignore): ifname = value.value # id defines the interface, will be appended to following snmp get id = value.oid_index if not id: id = value.oid.split(".")[-1] opstatus = ifstatus[session.get(ifOperStatus+'.'+id).value] lastchangedate = lastchange2date(uptime,session.get(ifLastChange+'.'+id).value) if args.down == 'n': x.add_row([ifname,opstatus,lastchangedate]) else: if opstatus == 'down': x.add_row([ifname,opstatus,lastchangedate]) print(x.get_string())
class SNMPBaseWorker(object, metaclass=ABCMeta): ses = None def __init__(self, ip: Optional[str], community='public', ver=2): if ip is None or ip == '': raise DeviceImplementationError(gettext('Ip address is required')) self._ip = ip self._community = community self._ver = ver def start_ses(self): if self.ses is None: self.ses = Session( hostname=self._ip, community=self._community, version=self._ver ) def set_int_value(self, oid: str, value): self.start_ses() return self.ses.set(oid, value, 'i') def get_list(self, oid) -> Generator: self.start_ses() for v in self.ses.walk(oid): yield v.value def get_list_keyval(self, oid) -> Generator: self.start_ses() for v in self.ses.walk(oid): snmpnum = v.oid.split('.')[-1:] yield v.value, snmpnum[0] if len(snmpnum) > 0 else None def get_item(self, oid): self.start_ses() v = self.ses.get(oid).value if v != 'NOSUCHINSTANCE': return v
def getLastChangeTime(): session = Session(hostname='10.127.2.61', community='aswani', version=2) lChange = session.get('.1.3.6.1.4.1.1916.1.42.1.1.1.2.1') return(lChange.value)
mib_onu_pon_num = "1.3.6.1.4.1.5875.800.3.9.3.4.1.12" pon_name_list = snmpSession.walk('1.3.6.1.4.1.5875.800.3.9.3.4.1.2') indice = [] for j in range(1,17): for i, elem in enumerate(pon_name_list): if olt_port+"/"+str(j)+"\'" == str(elem).split()[2]: indice.append(i) key = 0 result = {} for i in indice: key = key+1 mib_port = str(pon_name_list[i]).split()[3][41:][:-2] readport = snmpSession.get(mib_status+"."+mib_port) ponNumOnu = snmpSession.get(mib_onu_pon_num+"."+mib_port) status_pon = str(readport).split()[1][-2:-1] numOnu = str(ponNumOnu).split()[1][7:-1] result.update({key:[status_pon,numOnu]}) port_down = [] for i in range(1,len(result)+1): if int(result[i][0]) == 0 and int(result[i][1]) > alarm: port_down.append(i) if len(port_down) >= 1: print ("Slot "+olt_port+" PONs "+str(port_down)+" Down") sys.exit(2)
def _getSnmpValue(self, oid): session = Session(hostname=self.ip, community='public', version=2) value = session.get(oid).value self.logger.debug("%s: %s" % (oid, value)) return value
def getLastChangeTime(): session = Session(hostname='IP address', community='community', version=2) lChange = session.get('.1.3.6.1.4.1.1916.1.42.1.1.1.2.1') return(lChange.value)