def get_snmp_data(self): try: my_device = Session(ipaddress=self.ip) data = my_device.get_some( oids=[NAME_OID, LOCATION_OID, TEMPERATURE_OID]) self.name = data[0][1] self.location = data[1][1] self.temperature = float(data[2][1]) if self.temperature < 50.0: # This is in C, need to convert to F self.temperature = (float(self.temperature) * (9.0 / 5.0)) + 32.0 except Exception as e: print(str(e)) self.name = '' self.location = '' self.temperature = 0.0 self.result = { 'name': self.name, 'location': self.location, 'temperature': self.temperature } return
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
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 intstat(ip): ip_stat = {} list1 = [] list2 = [] dict_intf = {'1': 'fa0/0', '2': 'fa1/0', '3': 'fa1/1', '4': 'fa0/1'} dict_status = {'1': 'up', '2': 'down'} sess = Session(hostname=ip, community='public', version=2) sys = sess.walk(oids=u'.1.3.6.1.2.1.2.2.1.8') count = 0 for item in sys: int1 = '{oid}.{oid_index} {snmp_type} = {value}'.format( oid=item.oid, oid_index=item.oid_index, snmp_type=item.snmp_type, value=item.value) add3 = re.split(r'\s', int1) add4 = add3[0].split('.') list1.append(add4[-1]) list2.append(add3[-1]) count += 1 for i in range(0, count): int_name = dict_intf[list1[i]] int_stat = dict_status[list2[i]] ip_stat[int_name] = int_stat return ip_stat
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_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 walk_oids(host, port, oids, community, timeout, retries): session = Session(hostname=host, remote_port=port, community=community, version=2, use_numeric=True, use_long_names=True, timeout=timeout, retries=retries) for oid in oids: system_items = session.walk(oid) for item in system_items: yield item.oid[1:]+"."+item.oid_index, str((item.value).encode('ascii', 'ignore'))
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 get_lldp_a3_dlink(a3_arg, element_arg, cfg_ini): #-----------------------------------Первый A3----------------------------------------------------------------------- session_a3_1 = Session(hostname=a3_arg, community='ntcore', version=2) # Достаем Agg_Ports oid_lldp = session_a3_1.walk('.1.2.840.802.10006.300.43.1.2.1.1.24') for item_agg in oid_lldp: #Проверяем порт на участие в Agg if item_agg.value == u'1': tmp_parse = [] for q in str(item_agg.oid).split('.'): tmp_parse.append(q) ports_1.append(str(tmp_parse[12])) #Ищем элемент на портах и линк А3-А3 session_a3_1 = Session(hostname=a3_arg, community='ntcore', version=2) oid_lldp = session_a3_1.walk('.1.0.8802.1.1.2.1.4.1.1.9') for item in oid_lldp: if element_arg in str(item.value) or cfg_ini['A3'][a3_arg] in str(item.value).lower(): tmp_parse = [] for q in str(item.oid).split('.'): tmp_parse.append(q) ports_1.append(str(tmp_parse[12])) print (a3_arg) print("Элемент " + element_arg + " найден на порту: " + str(ports_1)) print ('--------------------------------------------------------') #-----------------------------------Второй A3----------------------------------------------------------------------- session_a3_2 = Session(hostname=cfg_ini['A3'][a3_arg], community='ntcore', version=2) # Достаем Agg_Ports oid_lldp = session_a3_2.walk('.1.2.840.802.10006.300.43.1.2.1.1.24') for item_agg in oid_lldp: #Проверяем порт на участие в Agg if item_agg.value == u'1': tmp_parse = [] for q in str(item_agg.oid).split('.'): tmp_parse.append(q) ports_2.append(str(tmp_parse[12])) #Ищем элемент на портах и линк А3-А3 session_a3_2 = Session(hostname=cfg_ini['A3'][a3_arg], community='ntcore', version=2) oid_lldp = session_a3_2.walk('.1.0.8802.1.1.2.1.4.1.1.9') for item in oid_lldp: if element_arg in str(item.value) or a3_arg in str(item.value).lower(): tmp_parse = [] for q in str(item.oid).split('.'): tmp_parse.append(q) ports_2.append(str(tmp_parse[12])) print (cfg_ini['A3'][a3_arg]) print("Элемент " + element_arg + " найден на порту: " + str(ports_2)) print ('--------------------------------------------------------') return (ports_1, ports_2)
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())
def create_snmp_session(self): self.session = Session( hostname=self.options.hostname, community=self.options.community, version=int(self.options.version), security_username=self.options.security_name, security_level=self.options.security_level, auth_protocol=self.options.auth_protocol, auth_password=self.options.auth_password, privacy_protocol=self.options.priv_protocol, privacy_password=self.options.priv_password, )
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 get_lldp_a3_cisco(a3_arg, element_arg): #Первый A3 session_a3_1 = Session(hostname=a3_arg, community='ntcore', version=2) oid_lldp = session_a3_1.walk('.1.0.8802.1.1.2.1.4.1.1.9') for item in oid_lldp: if element_arg in str(item.value): #print "FIND" #print '{oid}.{oid_index} {snmp_type} = {value}'.format( #oid=item.oid, #oid_index=item.oid_index, #snmp_type=item.snmp_type, #value=item.value #) tmp_parse = [] for q in str(item.oid).split('.'): tmp_parse.append(q) ports_1.append(str(tmp_parse[12])) print (a3_arg) print("Элемент " + element_arg + " найден на порту: " + str(ports_1)) print ("Магистральные порты: " + cfg_ini['Agg_links_cisco']['cisco_po1'] + ", " +cfg_ini['Agg_links_cisco']['cisco_po2']) print ('--------------------------------------------------------') #Второй A3 session_a3_2 = Session(hostname=cfg_ini['A3'][a3_arg], community='ntcore', version=2) oid_lldp = session_a3_2.walk('.1.0.8802.1.1.2.1.4.1.1.9') for item in oid_lldp: if element_arg in str(item.value): tmp_parse = [] for q in str(item.oid).split('.'): tmp_parse.append(q) ports_2.append(str(tmp_parse[12])) print (cfg_ini['A3'][a3_arg]) print("Элемент " + element_arg + " найден на порту: " + str(ports_2)) print ("Магистральные порты: " + cfg_ini['Agg_links_cisco']['cisco_po1'] + ", " + cfg_ini['Agg_links_cisco']['cisco_po2']) print ('--------------------------------------------------------\n') return (ports_1, ports_2)
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
class CiscoIpSlaChecker: STATUS_OK = 0 STATUS_WARNING = 1 STATUS_CRITICAL = 2 STATUS_UNKNOWN = 3 # Verbosity levels V_NONE = 0 V_INFO = 1 V_DEBUG = 2 def __init__(self): self.status = None self.message = None self.perfdata = None self.session = None self.options = None self.rtt_dict = dict() def run(self): self.parse_options() try: self.create_snmp_session() self.read_rtt_entries() except EasySNMPError as e: self.add_status(self.STATUS_UNKNOWN) self.message = "SNMP error checking {}, {}".format(self.options.hostname, e) else: if "list" == self.options.mode: self.list_rtt() elif "check" == self.options.mode: self.check() self.print_output() return self.status def parse_options(self): parser = argparse.ArgumentParser( description="Monitoring check plugin to check Cisco SLA status for one or more entries" ) parser.add_argument("-H", "--hostname", help="Hostname or ip-address") parser.add_argument("-v", "--version", default="2", choices=["1", "2", "3"], help="SNMP version (default '2')") parser.add_argument("-c", "--community", default="public", help="SNMP Community (default 'public')") parser.add_argument("-u", "--security-name", help="SNMP v3 security name (username)") parser.add_argument("-l", "--security-level", default="authPriv", choices=["noAuthNoPriv", "authNoPriv", "authPriv"], help="SNMP v3 security level (default 'authPriv')") parser.add_argument("-p", "--password", help="SNMP v3 password (used for both authentication and privacy)") parser.add_argument("-a", "--auth-protocol", default="SHA", choices=["MD5", "SHA"], help="SNMP v3 authentication protocol (default 'SHA')") parser.add_argument("-A", "--auth-password", help="SNMP v3 authentication password, overrides --password if set") parser.add_argument("-x", "--priv-protocol", default="AES", choices=["DES", "AES"], help="SNMP v3 privacy protocol (default 'AES')") parser.add_argument("-X", "--priv-password", help="SNMP v3 privacy password, overrides --password if set") parser.add_argument("-m", "--mode", choices=["list", "check"], help="Operation mode") parser.add_argument("-e", "--entries", default="all", help="SLA entry (or entries) to check, specify as 'all', " "a single value or comma-separated list") parser.add_argument("--perf", action="store_true", help="Return perfdata") parser.add_argument("--critical-pct", default=None, type=float, help="Critical threshold in percentage of failed SLAs (default '100')") parser.add_argument("--warning-pct", default=None, type=float, help="Warning threshold in percentage of failed SLAs (default '50')") parser.add_argument("--critical", default=None, type=int, help="Critical threshold in amount of failed SLAs") parser.add_argument("--warning", default=None, type=int, help="Warning threshold in amount of failed SLAs") parser.add_argument("--verbose", default=0, type=int, choices=[0, 1, 2], help="Verbose output") self.options = parser.parse_args() # Set default warning and critical levels if they are not specified at all if self.options.critical is None and self.options.critical_pct is None: self.options.critical_pct = 100 if self.options.warning is None and self.options.warning_pct is None: self.options.warning_pct = 50 # Copy password to auth-password and priv-password if applicable if self.options.auth_password is None and self.options.password is not None: self.options.auth_password = self.options.password if self.options.priv_password is None and self.options.password is not None: self.options.priv_password = self.options.password if not self.are_options_valid(): print("Run with --help for usage information") print("") exit(0) self.print_msg(self.V_DEBUG, "Using parameters:") self.print_msg(self.V_DEBUG, " Hostname: {}".format(self.options.hostname)) self.print_msg(self.V_DEBUG, " SNMP-version: {}".format(self.options.version)) self.print_msg(self.V_DEBUG, " Community: {}".format(self.options.community)) self.print_msg(self.V_DEBUG, " Security-name: {}".format(self.options.security_name)) self.print_msg(self.V_DEBUG, " Security-level: {}".format(self.options.security_level)) self.print_msg(self.V_DEBUG, " Password: {}".format(self.options.password)) self.print_msg(self.V_DEBUG, " Auth-protocol: {}".format(self.options.auth_protocol)) self.print_msg(self.V_DEBUG, " Auth-password: {}".format(self.options.auth_password)) self.print_msg(self.V_DEBUG, " Priv-protocol: {}".format(self.options.priv_protocol)) self.print_msg(self.V_DEBUG, " Priv-password: {}".format(self.options.priv_password)) self.print_msg(self.V_DEBUG, " Mode: {}".format(self.options.mode)) self.print_msg(self.V_DEBUG, " SLA entries: {}".format(self.options.entries)) self.print_msg(self.V_DEBUG, " Perf-data: {}".format(self.options.perf)) self.print_msg(self.V_DEBUG, " Critical-pct: {}".format(self.options.critical_pct)) self.print_msg(self.V_DEBUG, " Warning-pct: {}".format(self.options.warning_pct)) self.print_msg(self.V_DEBUG, " Critical: {}".format(self.options.critical)) self.print_msg(self.V_DEBUG, " Warning: {}".format(self.options.warning)) self.print_msg(self.V_DEBUG, " Verbosity: {}".format(self.options.verbose)) self.print_msg(self.V_DEBUG, "") def are_options_valid(self): if not self.options.hostname: print("You must specify a hostname") return False if not self.options.mode: print("You must specify a operation mode") return False if self.options.mode == "check" and not self.options.entries: print("You must specify SLA-entries for check-mode (use list-mode to list existing entries)") return False return True def print_msg(self, minimum_verbosity_level, msg): """ :param minimum_verbosity_level: Minimum verbosity level needed for the message to be printed :param msg: The message to print :return: """ if self.options.verbose >= minimum_verbosity_level: print(msg) def print_output(self): """ Prints the final output (in Nagios plugin format if self.status is set) :return: """ output = "" if self.status == self.STATUS_OK: output = "OK" elif self.status == self.STATUS_WARNING: output = "Warning" elif self.status == self.STATUS_CRITICAL: output = "Critical" elif self.status == self.STATUS_UNKNOWN: output = "Unknown" if self.message: if len(output): output += " - " output += self.message if self.perfdata: if len(output): output += " | " output += self.perfdata print(output) def create_snmp_session(self): self.session = Session( hostname=self.options.hostname, community=self.options.community, version=int(self.options.version), security_username=self.options.security_name, security_level=self.options.security_level, auth_protocol=self.options.auth_protocol, auth_password=self.options.auth_password, privacy_protocol=self.options.priv_protocol, privacy_password=self.options.priv_password, ) def add_status(self, status): """ Set the status only if it is more severe than the present status The order of severity being OK, WARNING, CRITICAL, UNKNOWN :param status: Status to set, one of the self.STATUS_xxx constants :return: The current status """ if self.status is None or status > self.status: self.status = status def read_rtt_entries(self): # Get SLA entry info self.rtt_dict = dict() rtt_ctrl_admin_entries = self.session.walk(".1.3.6.1.4.1.9.9.42.1.2.1.1") for item in rtt_ctrl_admin_entries: oid_parts = str(item.oid).split(".") rtt_entry = oid_parts[-1] rtt_info_type = oid_parts[-2] if rtt_entry not in self.rtt_dict: self.rtt_dict[rtt_entry] = dict() if "2" == rtt_info_type: # rttMonCtrlAdminOwner (2) self.rtt_dict[rtt_entry]["owner"] = str(item.value) elif "3" == rtt_info_type: # rttMonCtrlAdminTag (3) self.rtt_dict[rtt_entry]["tag"] = str(item.value) elif "4" == rtt_info_type: # rttMonCtrlAdminRttType (3) self.rtt_dict[rtt_entry]["type"] = str(item.value) # Get SLA entry status rtt_ctrl_oper_entries = self.session.walk(".1.3.6.1.4.1.9.9.42.1.2.9.1") for item in rtt_ctrl_oper_entries: oid_parts = str(item.oid).split(".") rtt_entry = oid_parts[-1] rtt_info_type = oid_parts[-2] if "5" == rtt_info_type: # rttMonCtrlOperConnectionLostOccurred (5) if item.value == "1": self.rtt_dict[rtt_entry]["conn_lost_occured"] = True else: self.rtt_dict[rtt_entry]["conn_lost_occured"] = False elif "6" == rtt_info_type: # rttMonCtrlOperTimeoutOccurred (6) if item.value == "1": self.rtt_dict[rtt_entry]["timeout_occured"] = True else: self.rtt_dict[rtt_entry]["timeout_occured"] = False elif "7" == rtt_info_type: # rttMonCtrlOperOverThresholdOccurred (7) if item.value == "1": self.rtt_dict[rtt_entry]["over_thres_occured"] = True else: self.rtt_dict[rtt_entry]["over_thres_occured"] = False elif "10" == rtt_info_type: # rttMonCtrlOperState (10) # http://tools.cisco.com/Support/SNMP/do/BrowseOID.do?local=en&translate=Translate&objectInput=1.3.6.1.4.1.9.9.42.1.2.9.1.10 if item.value == "6": self.rtt_dict[rtt_entry]["in_active_state"] = True else: self.rtt_dict[rtt_entry]["in_active_state"] = False def list_rtt(self): """ Reads the list of available SLA entries for the device and prints out a list :return: """ sla_list = list() inactive_sla_list = list() for rtt_entry in self.rtt_dict: rtt_id = "{0}".format(rtt_entry) if self.rtt_dict[rtt_entry]["tag"]: rtt_id += " (tag: {0})".format(self.rtt_dict[rtt_entry]["tag"]) if self.rtt_dict[rtt_entry]["in_active_state"]: sla_list.append(" {0}".format(rtt_id)) else: inactive_sla_list.append(" {0} (inactive)".format(rtt_id)) sla_list.extend(inactive_sla_list) if len(sla_list) == 0: self.message = "No SLAs available" else: self.message = "SLAs available:\n" for sla in sla_list: self.message += sla + "\n" def check(self): messages = [] if self.options.entries == "all": requested_entries = self.rtt_dict.keys() else: requested_entries = self.options.entries.replace(" ", "").split(",") # Initialize status to OK (if status is not set yet) self.add_status(self.STATUS_OK) ok_count = 0 failed_count = 0 for requested_entry in requested_entries: if requested_entry not in self.rtt_dict: self.message = "SLA {0} does not exist".format(requested_entry) self.add_status(self.STATUS_UNKNOWN) return else: rtt_id = "{0}".format(requested_entry) if self.rtt_dict[requested_entry]["tag"]: rtt_id += " (tag: {0})".format(self.rtt_dict[requested_entry]["tag"]) if self.rtt_dict[requested_entry]["in_active_state"]: if self.rtt_dict[requested_entry]["timeout_occured"]: failed_count += 1 messages.append("Timeout for SLA {0}".format(rtt_id)) else: ok_count += 1 else: messages.append("SLA {0} not active".format(rtt_id)) self.add_status(self.STATUS_WARNING) if failed_count + ok_count == 0: messages.append("No SLAs checked") self.add_status(self.STATUS_UNKNOWN) return failed_pct = round(float(failed_count) / (failed_count + ok_count) * 100, 1) # Check percentage thresholds (if set) if self.options.critical_pct is not None and failed_pct >= self.options.critical_pct: self.add_status(self.STATUS_CRITICAL) if self.options.warning_pct is not None and failed_pct >= self.options.warning_pct: self.add_status(self.STATUS_WARNING) # Check absolute thresholds (if set) if self.options.critical is not None and failed_count >= self.options.critical: self.add_status(self.STATUS_CRITICAL) if self.options.warning is not None and failed_count >= self.options.warning: self.add_status(self.STATUS_WARNING) if failed_count: # Don't show percentage-failed when only checking one SLA if failed_count + ok_count == 1: messages.insert(0, "{0} Failed".format(failed_count)) else: messages.insert(0, "{0} Failed ({1}%)".format(failed_count, failed_pct)) if ok_count: messages.insert(0, "{0} OK".format(ok_count)) if messages: self.message = ", ".join(messages) if self.options.perf: self.perfdata = "'Failed%'={0}%".format(failed_pct) if self.options.critical_pct and self.options.warning_pct: self.perfdata += ";{0};{1};0;100".format(self.options.warning_pct, self.options.critical_pct)
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)
for o in oids['OIDs']: devClass = o['class'] oList = o['OIDlist'] queryDict[devClass] = [] for oid in oList: oidName = oid['name'] oidNum = oid['oid'] queryDict[devClass].append(oidNum) for device in devices['devices']: ipAddr = device['ip'] name = device['name'] devClass = device['type'] community = device['rocomm'] try: session = Session(hostname=ipAddr, community=community, version=2, timeout=snmpTimeout, retries=0) #print "Device %s (%s) will poll oids %s" % (name, ipAddr, queryDict[devClass]) for o in queryDict[devClass]: x= session.walk(o) for val in x: #print "%s: %s" % (val.oid_index, val.value) pass except easysnmp.EasySNMPTimeoutError, e: print "Device %s (%s) timed out when requesting oid %s" % (name, ipAddr, o) except easysnmp.EasySNMPError, e: print "Non-timeout error from %s (%s) for oid %s" % (name, ipAddr, o) #print "OIDs:" #pprint.pprint(queryDict) end = time.time()
# check_command: check_pon_fiberhome!10.10.10.1!1 #----------------------------------------------------------------------- __author__ = 'Jorge Luiz Taioque' __version__= 1.0 from easysnmp import Session import sys olt_ip = sys.argv[1] olt_port = sys.argv[2] #Alarm only PON ports that has more than this value (variable [alarm] value) alarm = 2 snmpSession = Session(hostname=olt_ip, community='adsl', version=2) mib_status = "1.3.6.1.4.1.5875.800.3.9.3.4.1.5" 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:
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 __init__(self, ip, community): # Do the normal things for any network object. self.hostinit(ip) # Initiate SNMP self.session = Session(hostname=str(self.ip), community=community, version=1)
def start_ses(self): if self.ses is None: self.ses = Session( hostname=self._ip, community=self._community, version=self._ver )
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)
class Router(Host): def __init__(self, ip, community): # Do the normal things for any network object. self.hostinit(ip) # Initiate SNMP self.session = Session(hostname=str(self.ip), community=community, version=1) @property def routes(self): return self.__routes @routes.setter def routes(self, data): print('route set on', self.ip) self.__routes = data def walk(self, mib): # Walks the specified mib try: responses = self.session.walk(mib) return responses except easysnmp.exceptions.EasySNMPNoSuchNameError: # Probably means that you're hitting the wrong kind of device print('nosuchname') return False except easysnmp.exceptions.EasySNMPTimeoutError: # Either the community string is wrong, or you're pinging dead space print('timeout') return False def getArpTable(self): # A walk of the ARP table, gives list of dicts print('Scanning ARP table for router at:', self.ip) # MIB for ARP tables mib = 'ipNetToMediaPhysAddress' responses = self.walk(mib) arpTable = [] self.arpByMac = {} self.arpByIp = {} # Conditional, so that we don't error on empty responses if responses: ignored = 0 errors = 0 for response in responses: try: # Validation occurs in the decoding, just move on if they # throw assertion errors. mac = Mac(response.value, encoding='utf-16') ip = Ip(response.oid_index, encoding='snmp') #print('MAC: ' + str(mac) + ' IP: ' + str(ip)) values = {} values['mac'] = str(mac) values['ip'] = str(ip) # We also want to know where the ARP record came from. values['source'] = str(self.ip) # We ignore data points that have to do with locally # administered MAC addresses. localMacs = ['2', '6', 'a', 'e'] if values['mac'][1] in localMacs: ignored += 1 else: arpTable.append(values) self.arpByMac[mac] = ip self.arpByIp[ip] = mac except AssertionError: # Malformed input is to be ignored. errors += 1 pass print('Recorded', len(arpTable), 'ARP values with', errors, 'errors, ignoring', ignored, 'virtual MAC addresses.') return arpTable def getRoutingTable(self): print('Scanning routing table for router at:', self.ip) # Walk the routing table mib = 'ipCidrRouteTable' responses = self.walk(mib) errors = 0 routes = {} # Internally, we'll want to do lookups, so dict. print('Recieved', len(responses), 'SNMP responses from', self.ip) for r in responses: try: # An assumption is that the destinations come first. if r.oid == 'ipCidrRouteDest': # Introduce the route. routes[r.oid_index] = {'destination':Ip(r.value), 'router':self.ip} # The other conditions just add values. elif r.oid == 'ipCidrRouteMask': routes[r.oid_index]['netmask'] = Netmask(r.value) elif r.oid == 'ipCidrRouteNextHop': routes[r.oid_index]['nexthop'] = Ip(r.value) except KeyError: # Would mean that a value came in without our seeing the # destination first. errors += 1 # The index on this is useless outside of populating the routes. # I'm going to do a single pass to make a more useful index. self.routes = {} for r in routes.values(): self.routes[r['destination']+str(r['netmask'])+r['nexthop']] = r print('Parsed', len(self.routes), 'routes.') return self.routes