def main(): p = PluginHelper() # Warn on inactive level = 2 service_status = get_service_status(sys.argv[1]) if loaded(service_status)[0] is False: p.exit(3, "%s - %s" % (service_status['name'], loaded(service_status)[1]), "\n" + service_status['unparsed']) active = service_status['headers']['Active'][0] if active.startswith("inactive") or active.startswith('failed'): p.add_status(level) elif active.startswith("active"): p.add_status(0) else: p.add_status(3) p.add_summary("%s - %s" % ( service_status['name'], active)) p.add_long_output("\n" + service_status['unparsed']) p.exit()
class testPluginHelper(unittest.TestCase): def setUp(self): self.argv_store = sys.argv from pynag.Plugins import PluginHelper self.my_plugin = PluginHelper() self.my_plugin.parser.add_option('-F', dest='fakedata', help='fake data to test thresholds') sys.stdout = StringIO() def tearDown(self): sys.argv = self.argv_store sys.stdout = original_stdout def run_expect(self, case, value, expected_exit): sys.argv = [sys.argv[0]] + case.split() + ('-F %s' % value).split() self.my_plugin.parse_arguments() self.my_plugin.add_status(pynag.Plugins.ok) self.my_plugin.add_summary(self.my_plugin.options.fakedata) self.my_plugin.add_metric('fakedata', self.my_plugin.options.fakedata) try: self.my_plugin.check_all_metrics() self.my_plugin.exit() except SystemExit, e: self.assertEquals(type(e), type(SystemExit())) self.assertEquals(e.code, expected_exit) except Exception, e: self.fail('unexpected exception: %s' % e)
def main(): helper = PluginHelper() helper.parser.add_option('-w', help='warning free (X% or XM)', dest='warning') helper.parser.add_option('-c', help='critical free (X% or XM)', dest='critical') helper.parse_arguments() warn = helper.options.warning crit = helper.options.critical memory = getMemory() if helper.options.warning is not None: warn = helper.options.warning if re.match('.*%$', warn): warn = str(memory['total'] * int(re.search('\d*', warn).group(0)) / 100) else: warn = '0' if helper.options.critical is not None: crit = helper.options.critical if re.match('.*%$', crit): crit = str(memory['total'] * int(re.search('\d*', crit).group(0)) / 100) else: crit = '0' helper.status(ok) status = "OK" if memory['totalfree'] <= int(warn): helper.status(warning) status = "WARNING" if memory['totalfree'] <= int(crit): helper.status(critical) status = "CRITICAL" helper.add_summary(status + ': Memory free: %(totalfree)s %% (%(free)s %% including buffers/cached)' % {'totalfree': (round((float(memory['totalfree']) / float(memory['total']) * 100), 1 )), 'free': (round((float(memory['free']) / float(memory['total']) * 100), 1 ))}) helper.add_metric(label='total',value=memory['total']) helper.add_metric(label='free',value=memory['free']) helper.add_metric(label='totalfree',value=memory['totalfree'], warn=warn+'..0', crit=crit+'..0') helper.add_metric(label='used',value=memory['used']) helper.add_metric(label='buffers',value=memory['buffers']) helper.add_metric(label='cached',value=memory['cached']) helper.add_metric(label='swapcached',value=memory['swapcached']) helper.check_all_metrics() helper.exit()
def check_metric(self): """Check if the metric value is within the threshold range, and exits with status code, message and perfdata. """ # Get values metric_values = self._get_metric_values() unit = self._AZURE_METRICS_UNIT_SYMBOLS.get( self._metric_properties['unit']) if unit is None: unit = '' # Test if value to display if metric_values is None: message = 'No value available for metric {}'.format(self['metric']) if self['dimension'] is not None: message += ' and dimension {}'.format(self['dimension']) self.nagios_exit(Plugins.UNKNOWN, message) # PluginHelper of pynag import # https://pynag.readthedocs.io/en/latest/pynag.Plugins.html?highlight=check_threshold#pynag.Plugins.PluginHelper p = PluginHelper() # For each value, declare metric with according thresholds for metric_idx in metric_values: p.add_metric(label=metric_idx, value=metric_values[metric_idx], uom=unit, warn=self['warning'], crit=self['critical']) # Test all metrics according to there thresholds p.check_all_metrics() # Add global summary for output p.add_summary(self._metric_properties['name']['localizedValue']) # Exit and display plugin output p.exit()
def main(): p = PluginHelper() # Warn on inactive level = 2 service_status = get_service_status(sys.argv[1]) if loaded(service_status)[0] is False: p.exit(3, "%s - %s" % (service_status['name'], loaded(service_status)[1]), "\n" + service_status['unparsed']) active = service_status['headers']['Active'][0] if active.startswith("inactive") or active.startswith('failed'): p.add_status(level) elif active.startswith("active"): p.add_status(0) else: p.add_status(3) p.add_summary("%s - %s" % (service_status['name'], active)) p.add_long_output("\n" + service_status['unparsed']) p.exit()
# check_stuff.py Takes any arguments from the command_line and treats them as performance metrics. from pynag.Plugins import PluginHelper my_plugin = PluginHelper() my_plugin.parse_arguments() # Any perfdatastring added as argument will be treated as a performance metric for i in my_plugin.arguments: my_plugin.add_metric(perfdatastring=i) my_plugin.check_all_metrics() my_plugin.exit()
units =['', '', '', '%', '%', '%', '', 'Byte', '', '' ] ############## ## Main ## ############### if __name__ == '__main__': # The default return value should be always OK helper.status(ok) # shows the list of possible types if the flag is set if flag_list == True: for w,v in zip(names, descriptions): print w + ' = ' + v helper.status(unknown) helper.exit(summary='This is just a list and not a check!') # verify that a hostname is set verify_host(host, helper) # open session after validated host sess = netsnmp.Session(Version=version, DestHost=host, Community=community) # verify, that status(/type) parameter is not empty if (status == None) or (status not in names): helper.status(unknown) helper.exit(summary='Argument -t is missing or false!') # snmp gets for all oids in type-list ind = names.index(status) value = get_data(sess, oids[ind],helper)
sess = netsnmp.Session(Version=version, DestHost=host, Community=community) # If the --scan option is set, we show all components and end the script if scan: scan_ilo() # Show always the product name and the serial number in the summary product_name = get_data(sess, oid_product_name, helper) serial_number = get_data(sess, oid_serial_numb, helper) helper.add_summary('%s - Serial number:%s' % (product_name, serial_number)) # Verify that there is an input for the amount of components if input_phy_drv == '' or input_phy_drv is None: helper.exit( summary="Amount of physical drives must be specified (--drives)", exit_code=unknown, perfdata='') if input_pwr_sply == '' or input_pwr_sply is None: helper.exit( summary="Amount of power supplies must be specified (--ps)", exit_code=unknown, perfdata='') if input_fan == '' or input_fan is None: helper.exit(summary="Amount of fans must be specified (--fan)", exit_code=unknown, perfdata='') # Check the global status check_global_status(storage_flag, 'Global storage', oid_storage) check_global_status(system_flag, 'Global system', oid_system) check_global_status(power_supply_flag, 'Global power supply',
#Claculate UTC-time from local-time if remote_time_utc_dir == '+': remote_timestamp -= datetime.timedelta(hours=remote_time_hours_offset, minutes=remote_time_minutes_offset) elif remote_time_utc_dir == '-': remote_timestamp += datetime.timedelta(hours=remote_time_hours_offset, minutes=remote_time_minutes_offset) try: # Windows will return the local time (not UTC), so we need to use the local time to compare # Force this this if '-l' or '--localtime' is set in commandline if windows or use_local : local_timestamp = datetime.datetime.now() time_type = 'Remote (Local)' else: # usually the we need the UTC time local_timestamp = datetime.datetime.utcnow() time_type = 'Remote (UTC)' #Calculate the offset between local and remote time offset = time.mktime(local_timestamp.timetuple()) - time.mktime(remote_timestamp.timetuple()) + 60 * o_tzoff helper.add_metric(label = 'offset', value = offset, uom = 's') helper.check_all_metrics() except IndexError: helper.exit(summary = 'remote device does not return a time value', exit_code = unknown, perfdata = '') #Print out plugin information and exit nagios-style helper.add_summary('%s: ' % (time_type) + datetime.datetime.fromtimestamp(time.mktime(remote_timestamp.timetuple())).strftime('%H:%M:%S') + '. Offset = %d s' % offset) helper.add_long_output('%s: ' % (time_type) + datetime.datetime.fromtimestamp(time.mktime(remote_timestamp.timetuple())).strftime('%Y.%m.%d %H:%M:%S')) helper.exit()
'Voltage L1-L2', 'Voltage L2-L3', 'Voltage L3-L1' ] ############## ## Main ## ############### if __name__ == '__main__': # The default return value should be always OK helper.status(ok) # shows the list of possible types if the flag is set if flag_list == True: for w, v in zip(names, descriptions): print w + ' = ' + v helper.status(unknown) helper.exit(summary='This is just a list and not a check!') # verify that a hostname is set verify_host(host, helper) # open session after validated host sess = netsnmp.Session(Version=version, DestHost=host, Community=community) # verify, that status(/type) parameter is not empty if (status == None) or (status not in names): helper.status(unknown) helper.exit(summary='Argument -t is missing or false!') # snmp gets for all oids in type-list ind = names.index(status) value = get_data(sess, basicoid + oid[ind], helper)
class PluginHelper(unittest.TestCase): def setUp(self): self.argv_store = sys.argv from pynag.Plugins import PluginHelper self.my_plugin = PluginHelper() self.my_plugin.parser.add_option('-F', dest='fakedata', help='fake data to test thresholds') sys.stdout = StringIO() def tearDown(self): sys.argv = self.argv_store sys.stdout = original_stdout def run_expect(self, case, value, expected_exit): sys.argv = [sys.argv[0]] + case.split() + ('-F %s' % value).split() self.my_plugin.parse_arguments() self.my_plugin.add_status(pynag.Plugins.ok) self.my_plugin.add_summary(self.my_plugin.options.fakedata) self.my_plugin.add_metric('fakedata', self.my_plugin.options.fakedata) try: self.my_plugin.check_all_metrics() self.my_plugin.exit() except SystemExit as e: self.assertEquals(type(e), type(SystemExit())) self.assertEquals(e.code, expected_exit) except Exception as e: self.fail('unexpected exception: %s' % e) else: self.fail('SystemExit exception expected') finally: signal.alarm(0) # Critical if "stuff" is over 20, else warn if over 10 # (will be critical if "stuff" is less than 0) def test_number_1(self): case = '--th=metric=fakedata,ok=0..10,warn=10..20' self.run_expect(case, -23, 2) def test_number_2(self): case = '--th=metric=fakedata,ok=0..10,warn=10..20' self.run_expect(case, 3, 0) def test_number_3(self): case = '--th=metric=fakedata,ok=0..10,warn=10..20' self.run_expect(case, 13, 1) def test_number_4(self): case = '--th=metric=fakedata,ok=0..10,warn=10..20' self.run_expect(case, 23, 2) # Same as above. Negative "stuff" is OK def test_number_5(self): case = '--th=metric=fakedata,ok=inf..10,warn=10..20' self.run_expect(case, '-23', 0) def test_number_6(self): case = '--th=metric=fakedata,ok=inf..10,warn=10..20' self.run_expect(case, '3', 0) def test_number_7(self): case = '--th=metric=fakedata,ok=inf..10,warn=10..20' self.run_expect(case, '13', 1) def test_number_8(self): case = '--th=metric=fakedata,ok=inf..10,warn=10..20' self.run_expect(case, '23', 2) # Critical if "stuff" is over 20, else warn if "stuff" is below 10 # (will be critical if "stuff" is less than 0) def test_number_9(self): case = '--th=metric=fakedata,warn=0..10,crit=20..inf' self.run_expect(case, '-23', 0) def test_number_10(self): case = '--th=metric=fakedata,warn=0..10,crit=20..inf' self.run_expect(case, '3', 1) def test_number_11(self): case = '--th=metric=fakedata,warn=0..10,crit=20..inf' self.run_expect(case, '13', 0) def test_number_12(self): case = '--th=metric=fakedata,warn=0..10,crit=20..inf' self.run_expect(case, '23', 2) # Critical if "stuff" is less than 1 def test_number_13(self): case = '--th=metric=fakedata,ok=1..inf' self.run_expect(case, '-23', 2) def test_number_14(self): case = '--th=metric=fakedata,ok=1..inf' self.run_expect(case, '0', 2) def test_number_15(self): case = '--th=metric=fakedata,ok=1..inf' self.run_expect(case, '13', 0) def test_number_16(self): case = '--th=metric=fakedata,ok=1..inf' self.run_expect(case, '23', 0) # 1-9 is warning, negative or above 10 is critical def test_number_17(self): case = '--th=metric=fakedata,warn=1..9,crit=^0..10' self.run_expect(case, '-23', 2) def test_number_18(self): case = '--th=metric=fakedata,warn=1..9,crit=^0..10' self.run_expect(case, '0', 0) def test_number_19(self): case = '--th=metric=fakedata,warn=1..9,crit=^0..10' self.run_expect(case, '7', 1) def test_number_20(self): case = '--th=metric=fakedata,warn=1..9,crit=^0..10' self.run_expect(case, '23', 2) # The only noncritical range is 5:6 def test_number_21(self): case = '--th=metric=fakedata,ok=5..6' self.run_expect(case, '-23', 2) def test_number_22(self): case = '--th=metric=fakedata,ok=5..6' self.run_expect(case, '0', 2) def test_number_23(self): case = '--th=metric=fakedata,ok=5..6' self.run_expect(case, '2', 2) def test_number_24(self): case = '--th=metric=fakedata,ok=5..6' self.run_expect(case, '5', 0) def test_number_25(self): case = '--th=metric=fakedata,ok=5..6' self.run_expect(case, '6', 0) def test_number_26(self): case = '--th=metric=fakedata,ok=5..6' self.run_expect(case, '7', 2) # Critical if "stuff" is 10 to 20 def test_number_27(self): case = '--th=metric=fakedata,ok=^10..20' self.run_expect(case, '-23', 0) def test_number_28(self): case = '--th=metric=fakedata,ok=^10..20' self.run_expect(case, '0', 0) def test_number_29(self): case = '--th=metric=fakedata,ok=^10..20' self.run_expect(case, '2', 0) def test_number_30(self): case = '--th=metric=fakedata,ok=^10..20' self.run_expect(case, '10', 2) def test_number_31(self): case = '--th=metric=fakedata,ok=^10..20' self.run_expect(case, '15', 2) def test_number_32(self): case = '--th=metric=fakedata,ok=^10..20' self.run_expect(case, '20', 2) def test_number_33(self): case = '--th=metric=fakedata,ok=^10..20' self.run_expect(case, '23', 0) # Cmdline thresholds pass but we insert a "hardcoded" metric with thresholds # which will also be evaluated def test_number_34(self): # Extra case with hardcoded thresholds self.my_plugin.add_metric('fakedata2', value='15', warn='0..10', crit='10..inf') case = '--th=metric=fakedata,ok=0..10,warn=10..20' self.run_expect(case, 3, 2) def test_number_35(self): # Extra case with hardcoded thresholds self.my_plugin.add_metric('fakedata2', value='9', warn='0..10', crit='10..inf') case = '--th=metric=fakedata,ok=0..10,warn=10..20' self.run_expect(case, 3, 1) def test_number_36(self): # Extra case with hardcoded thresholds self.my_plugin.add_metric('fakedata2', value='-4', warn='0..10', crit='10..inf') case = '--th=metric=fakedata,ok=0..10,warn=10..20' self.run_expect(case, 3, 0) def testTimeout(self): try: self.my_plugin.set_timeout(1) time.sleep(1) self.assertTrue(False, "Code should have timed out by now") except SystemExit as e: self.assertEquals(type(e), type(SystemExit())) self.assertEquals(e.code, pynag.Plugins.unknown) self.assertTrue(True, "Timeout occured in plugin, just like expected.")
p.parser.add_option('--url', dest='url', default=default_url) p.parse_arguments() p.check_all_metrics() p.show_legacy = True html = requests.get(p.options.url).content soup = BeautifulSoup(html) activitylist = soup.find('div', {'class': 'activityNumbers activityNumbersNew'}) activities = activitylist.findAll('div', recursive=False) p.add_metric('metrics_found', value=len(activities), warn='0..1') p.add_summary('%s metrics found on landspitali website' % (len(activities))) for i in activities: metric_name = i.get('class') metric_value = i.find('div', {'class': "todaysCount"}).text heading = i.find('div', {'class': 'heading'}) text = i.find('div', {'class': 'todaysText'}) # If string dag... is found, this is a counter for the whole day if 'dag...' in heading.text: uom = 'c' else: uom = '' p.add_metric(metric_name, metric_value, uom=uom) p.add_long_output("%s: %s %s %s" % (metric_name, heading.text, metric_value, text.text)) p.status(ok) p.exit()
"2" : "Alarmed" } if __name__ == "__main__": # verify that a hostname is set verify_host(host, helper) # The default return value should be always OK helper.status(ok) sess = netsnmp.Session(Version=version, DestHost=host, Community=community) # get the values if unit == "1": value = get_data(sess, unit1_oid, helper) elif unit == "2": value = get_data(sess, unit2_oid, helper) else: helper.exit(summary="Wrong unit specified", exit_code=unknown, perfdata='') # add the summary helper.add_summary("Unit status is: %s" % (status[value])) if value == "2": helper.status(critical) # Print out plugin information and exit nagios-style helper.exit()
sess = netsnmp.Session(Version=version, DestHost=host, SecLevel=seclevel, SecName=secname, AuthProto=authproto, AuthPass=authpass, PrivProto=privproto, PrivPass=privpass, Community=community) # If the --scan option is set, we show all components and end the script if scan: scan_ilo() # Show always the product name and the serial number in the summary product_name = get_data(sess, oid_product_name, helper) serial_number = get_data(sess, oid_serial_numb, helper) helper.add_summary('%s - Serial number:%s' % (product_name, serial_number)) # Verify that there is an input for the amount of components if input_phy_drv == '' or input_phy_drv is None: helper.exit(summary="Amount of physical drives must be specified (--drives)", exit_code=unknown, perfdata='') if input_pwr_sply == '' or input_pwr_sply is None: helper.exit(summary="Amount of power supplies must be specified (--ps)", exit_code=unknown, perfdata='') if input_fan == '' or input_fan is None: helper.exit(summary="Amount of fans must be specified (--fan)", exit_code=unknown, perfdata='') # Check the global status check_global_status(storage_flag, 'Global storage', oid_storage) check_global_status(system_flag,'Global system',oid_system) check_global_status(power_supply_flag,'Global power supply',oid_glob_power_supply) check_global_status(temp_flag,'Overall thermal environment',oid_glob_temp) check_global_status(temp_sens_flag,'Temperature sensors',oid_glob_temp_sens) check_global_status(fan_flag,'Fan(s)',oid_glob_fan) check_global_status(mem_flag,'Memory',oid_mem) # check if the server is powered on
if len(services) == 0: # if there are no running services, print the message print "no service running at host" # we don't want to return a icinga output, so we just end the script here quit() else: ############# # Here we check the service ############# ## convert the service name to a oid service_oid = convert_in_oid(service) # get the data result = attempt_get_data(sess, service_oid) if not result or result == "NOSUCHOBJECT": service_status = "NOT RUNNING" helper.status(critical) else: service_status = "RUNNING" helper.status(ok) helper.add_summary("Status of Service '" + service + "' is: " + service_status) # Print out plugin information and exit nagios-style helper.exit()
helper.parser.add_option('-C', '--community', dest='community', help='SNMP community of the SNMP service on target host.', default='public') helper.parser.add_option('-V', '--snmpversion', dest='version', help='SNMP version. (1 or 2)', default=2, type='int') helper.parser.add_option('-t', help="The type you want to monitor (inlet, outlet, sensor)", default="inlet", dest="typ") helper.parser.add_option('-i', help="The id of the outlet / sensor you want to monitor (1-99)", default="1", dest="id") helper.parse_arguments() # get the options id = helper.options.id typ = helper.options.typ host = helper.options.hostname version = helper.options.version community = helper.options.community # verify that there is a hostname set if host == "" or host == None: helper.exit(summary="Hostname must be specified", exit_code=unknown, perfdata='') # these dicts / definitions we need to get human readable values names = { 'C': 'Current', 'V': 'Voltage', 'c': 'Current', 'v': 'Voltage', 'P': 'Power', 'p': 'Power', } #cleanup: for the inlet we should read the available #sensors = { # 0: "rmsCurrent",
# Try to download the serverstatus page and do some basic data munging. try: start = time.time() website = urllib2.urlopen('%s://%s:%i/server-status?auto' % (my_plugin.options.protocol,my_plugin.options.hostname,my_plugin.options.port), None,my_plugin.options.timeout ) content= website.read().strip() # Split each parameter into a dict results = dict(re.split(':\s*', line) for line in content.split('\n')) results['OpenSlots']= results['Scoreboard'].count('.') results['ResponseTime']="{0:.4f}".format(time.time() - start) # Catch any Errors except urllib2.HTTPError, e: my_plugin.exit(summary="Cannot retrieve URL: HTTP Error Code %s" % e.code, long_output=str(e), exit_code=unknown) except urllib2.URLError, e: my_plugin.exit(summary="Cannot retrieve URL: Perhaps a bad protocol (ssl not supported)?" , long_output=str(e), exit_code=unknown) except Exception, e: my_plugin.exit(summary="Something horrible happened:", long_output=str(e), exit_code=unknown, perfdata='') # Lets Parse the data: my_plugin.add_summary( "%s seconds response time" % results['ResponseTime']) # and add metrics: my_plugin.add_metric( label='Total Accesses', value=results['Total Accesses'], uom='c', ) my_plugin.add_metric( label='Total kBytes', value=results['Total kBytes'], uom='kb', ) my_plugin.add_metric( label='CPULoad', value=float(results['CPULoad'])*100, uom='%', ) my_plugin.add_metric( label='Uptime', value=results['Uptime'], uom='c', ) my_plugin.add_metric( label='ReqPerSec', value=results['ReqPerSec'], )
# Create an instance of PluginHelper() helper = PluginHelper() # Optionally, let helper handle command-line arguments for us for example --threshold # Note: If your plugin needs any commandline arguments on its own (like --hostname) you should add them # before this step with helper.parser.add_option() helper.parse_arguments() # Here starts our plugin specific logic. Lets try to read /proc/loadavg # And if it fails, we exit immediately with UNKNOWN status try: content = open('/proc/loadavg').read() except Exception as e: helper.exit(summary="Could not read /proc/loadavg", long_output=str(e), exit_code=unknown, perfdata='') # We have read the contents of loadavg file. Lets put it in the summary of our plugin output: helper.add_summary("Load: %s" % content) # Read metrics from /proc/loadavg and add them as performance metrics load1,load5,load15,processes,last_proc_id = content.split() running,total = processes.split('/') # If we so desire we can set default thresholds by adding warn attribute here # However we decide that there are no thresholds by default and they have to be # applied on runtime with the --threshold option helper.add_metric(label='load1',value=load1) helper.add_metric(label='load5',value=load5)
import string import sys reload(sys) sys.setdefaultencoding('utf-8') from BeautifulSoup import BeautifulSoup from pynag.Plugins import PluginHelper,ok,warning,critical,unknown p = PluginHelper() default_url = 'http://www.isanicelandicvolcanoerupting.com' p.parser.add_option('--url', dest='url', default=default_url) p.parse_arguments() p.show_legacy = True html = requests.get(p.options.url).content soup = BeautifulSoup(html) answer = soup.find('h3').text p.add_summary('Source says: "%s"' % answer) if 'yes' in answer.lower(): p.status(warning) elif 'no' in answer.lower(): p.status(ok) else: p.status(unknown) p.check_all_metrics() p.exit()
remote_timestamp += datetime.timedelta(hours=remote_time_hours_offset, minutes=remote_time_minutes_offset) try: # Windows will return the local time (not UTC), so we need to use the local time to compare # Force this this if '-l' or '--localtime' is set in commandline if windows or use_local: local_timestamp = datetime.datetime.now() time_type = 'Remote (Local)' else: # usually the we need the UTC time local_timestamp = datetime.datetime.utcnow() time_type = 'Remote (UTC)' # Calculate the offset between local and remote time offset = time.mktime(local_timestamp.timetuple()) - time.mktime(remote_timestamp.timetuple()) + 60 * o_tzoff helper.add_metric(label='offset', value=offset, uom='s') helper.check_all_metrics() except IndexError: helper.exit(summary='remote device does not return a time value', exit_code=unknown, perfdata='') # Print out plugin information and exit nagios-style helper.add_summary( '%s: ' % (time_type) + datetime.datetime.fromtimestamp(time.mktime(remote_timestamp.timetuple())).strftime( '%H:%M:%S') + '. Offset = %d s' % offset) helper.add_long_output( '%s: ' % (time_type) + datetime.datetime.fromtimestamp(time.mktime(remote_timestamp.timetuple())).strftime( '%Y.%m.%d %H:%M:%S')) helper.exit()
import requests from BeautifulSoup import BeautifulSoup url = 'http://hagstofan.is' p = PluginHelper() p.parse_arguments() p.show_legacy = True tmp = requests.get(url) html = tmp.content soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES) keyfigures_table = soup.find('table', {'class': 'keyfigures_small'}) if not keyfigures_table: p.exit(unknown, "Could not find any table with class=keyfigures_small'") rows = keyfigures_table.findAll('tr') for row in rows: textdata = row.find('td', {'class': 'textdata'}) numberdata = row.find('td', {'class': 'numberdata'}) if not textdata or not numberdata: continue # Get the text content out of the <td> cells textdata = textdata.text numberdata = numberdata.text # clear some formatting numberdata = numberdata.replace('.', '').replace(',', '')
return tn.read_all() if __name__ == '__main__': plugin = PluginHelper() plugin.parser.add_option("-H","--hostname", help="Zookeeper's host", default='127.0.0.1') plugin.parser.add_option("-p","--port", help="Zookeeper's port", default='2181') plugin.parse_arguments() try: zk = ZkClient(plugin.options.hostname, plugin.options.port) except socket.error: plugin.status(critical) plugin.add_summary("Can't connect to {}:{}".format(plugin.options.hostname, plugin.options.port)) plugin.exit() try: if zk.cmd('ruok') != 'imok': plugin.status(critical) plugin.add_summary("Command 'ruok' failed") plugin.exit() except socket.error, socket.timeout: plugin.status(critical) plugin.add_summary("Can't connect to {}:{}".format(plugin.options.hostname, plugin.options.port)) plugin.exit() try: if zk.cmd('isro') != 'rw': plugin.status(critical) plugin.add_summary("Zookeeper is not read-write (network partition? quorum?)")
#!/usr/bin/python import os.path import sys pynagbase = os.path.abspath( os.path.join(os.path.dirname(__file__), os.path.pardir)) sys.path[0] = pynagbase # Standard init from pynag.Plugins import PluginHelper, ok # Create an instance of PluginHelper() my_plugin = PluginHelper() # Feed fake data for range checking my_plugin.parser.add_option('-F', dest='fakedata', help='fake data to test thresholds') # Activate my_plugin.parse_arguments() my_plugin.add_status(ok) my_plugin.add_summary(my_plugin.options.fakedata) my_plugin.add_metric('fakedata', my_plugin.options.fakedata) my_plugin.check_all_metrics() my_plugin.exit()
# Create an instance of PluginHelper() helper = PluginHelper() # Optionally, let helper handle command-line arguments for us for example --threshold # Note: If your plugin needs any commandline arguments on its own (like --hostname) you should add them # before this step with helper.parser.add_option() helper.parse_arguments() # Here starts our plugin specific logic. Lets try to read /proc/loadavg # And if it fails, we exit immediately with UNKNOWN status try: content = open('/proc/loadavg').read() except Exception, e: helper.exit(summary="Could not read /proc/loadavg", long_output=str(e), exit_code=unknown, perfdata='') # We have read the contents of loadavg file. Lets put it in the summary of our plugin output: helper.add_summary("Load: %s" % content) # Read metrics from /proc/loadavg and add them as performance metrics load1,load5,load15,processes,last_proc_id = content.split() running,total = processes.split('/') # If we so desire we can set default thresholds by adding warn attribute here # However we decide that there are no thresholds by default and they have to be # applied on runtime with the --threshold option helper.add_metric(label='load1',value=load1) helper.add_metric(label='load5',value=load5)
dest="version", default='2') helper.parser.add_option("-c", help="Snmp Comunity", dest="community", default='public') helper.parse_arguments() # Here starts our plugin specific logic. Lets try to read /proc/loadavg # And if it fails, we exit immediately with UNKNOWN status try: load(helper.options.mib) except Exception, e: helper.exit(summary="Could not read MIB file.", long_output=str(e), exit_code=unknown, perfdata='') m = Manager(helper.options.host, helper.options.community, int(helper.options.version)) formatstring = helper.options.value + ': %s' commandstring = "m." + helper.options.value content = eval(commandstring) helper.add_summary(formatstring % content) # Read metrics from /proc/loadavg and add them as performance metrics #load1,load5,load15,processes,last_proc_id = content.split() #running,total = processes.split('/') # If we so desire we can set default thresholds by adding warn attribute here
# before this step with helper.parser.add_option() helper.parser.add_option("-n", help="Interface name (regex)", dest="name", default='.') helper.parser.add_option("-H", help="Hostname or IP", dest="host", default='localhost') helper.parser.add_option("--Version", help="Snmp Version", dest="version", default='2') helper.parser.add_option("-c", help="Snmp Comunity", dest="community", default='public') helper.parse_arguments() # Here starts our plugin specific logic. Lets try to read /proc/loadavg # And if it fails, we exit immediately with UNKNOWN status try: load('IF-MIB') except Exception, e: helper.exit(summary="Could not read MIB file.", long_output=str(e), exit_code=unknown, perfdata='') m=Manager(helper.options.host,helper.options.community,int(helper.options.version)) mc = memcache.Client(['127.0.0.1:11211'], debug=0) p = re.compile(helper.options.name) values=['ifInOctets','ifOutOctets','ifInErrors','ifOutErrors','ifInUcastPkts','ifOutUcastPkts'] for interfaceKey in m.ifIndex: if p.search(str(m.ifDescr[interfaceKey])): for valuesKey in values: now=time.time() commandstr='m.'+valuesKey+"[%s]" % interfaceKey labelstr=str(m.ifDescr[interfaceKey])+'-'+valuesKey counthash=str(hash('checkinterfaces'+helper.options.host+labelstr)) timehash=str(hash('now'+helper.options.host+labelstr))
helper.status(critical) else: helper.status(unknown) helper.add_summary('global status is {}'.format(status)) if version == 1: details = json_data if version == 2: details = json_data['status'] for item in [ 'cassandra', 'diskSpace', 'dataSource', 'elasticsearch', 'jms', 'mail', 'mongo', 'rabbit', 'redis', 'solr', 'db', 'vault' ]: if item in details: item_status = details[item]['status'] helper.add_summary('{} status is {}'.format(item, item_status)) if helper.get_status() != critical and item_status == 'UNKNOWN': helper.status(unknown) elif item_status in ('DOWN', 'OUT_OF_SERVICE'): helper.status(critical) else: if version == 1: handle_version_1() if version == 2: handle_version_2() helper.check_all_metrics() helper.exit()
"--hostname", help="Zookeeper's host", default='127.0.0.1') plugin.parser.add_option("-p", "--port", help="Zookeeper's port", default='2181') plugin.parse_arguments() try: zk = ZkClient(plugin.options.hostname, plugin.options.port) except socket.error: plugin.status(critical) plugin.add_summary("Can't connect to {}:{}".format( plugin.options.hostname, plugin.options.port)) plugin.exit() try: if zk.cmd('ruok') != 'imok': plugin.status(critical) plugin.add_summary("Command 'ruok' failed") plugin.exit() except socket.error, socket.timeout: plugin.status(critical) plugin.add_summary("Can't connect to {}:{}".format( plugin.options.hostname, plugin.options.port)) plugin.exit() try: if zk.cmd('isro') != 'rw': plugin.status(critical)