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()
help="don't verify certificate", dest='verify', action='store_false', default=True) helper.parser.add_option( '-t', '--trust-store', help='trust store (PEM format) to use for TLS certificate validation', dest='truststore') helper.parser.add_option( '-m', '--metrics', help='comma separated list of metrics to display, they can be combined with thresholds', dest='metrics') helper.parser.add_option( '-u', '--user-credentials', help='user credentials in the format username:password', dest='credentials') helper.parse_arguments() health_endpoint = helper.options.url + '/health' metrics_endpoint = helper.options.url + '/metrics' contenttype_v1 = 'application/vnd.spring-boot.actuator.v1' contenttype_v2 = 'application/vnd.spring-boot.actuator.v2' get_args = {'verify': helper.options.verify} if helper.options.truststore: get_args['verify'] = helper.options.truststore if helper.options.credentials: get_args['auth'] = tuple(helper.options.credentials.split(':'))
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This script collects key figure metrics from hagstofan.is from pynag.Plugins import PluginHelper, ok, unknown 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
import random import sys reload(sys) sys.setdefaultencoding('utf-8') from BeautifulSoup import BeautifulSoup from pynag.Plugins import PluginHelper, ok, warning, critical, unknown p = PluginHelper() chars = string.letters + string.digits randomstring = ''.join([random.choice(chars) for i in xrange(4)]) # avoid cache default_url = 'http://landspitali.is' 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'})
#!/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()
import os import netsnmp sys.path.insert(1, os.path.join(sys.path[0], os.pardir)) from snmpSessionBaseClass import add_common_options, get_common_options, verify_host, attempt_get_data, walk_data from pynag.Plugins import PluginHelper,ok,critical # Create an instance of PluginHelper() helper = PluginHelper() # Add command line parameters add_common_options(helper) helper.parser.add_option('-s', '--service', help="The name of the service you want to monitor (-s scan for scanning)", dest="service", default='') helper.parser.add_option('-S', '--scan', dest = 'scan_flag', default = False, action = "store_true", help = 'Show all available services') helper.parse_arguments() # get the options host, version, community = get_common_options(helper) service = helper.options.service scan = helper.options.scan_flag # that is the base id base_oid = ".1.3.6.1.4.1.77.1.2.3.1.1" ''' # for check_snmp_service we need to adapt the service_get_data function def service_get_data(sess, host, version, community, oid): var = netsnmp.Varbind(oid) data = netsnmp.snmpget(var, Version=version, DestHost=host, Community=community) value = data[0]
# 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()
def cmd(self, word): """Connect and send a 4letter command to Zookeeper. """ # Zookeeper closes the socket after every command, so we must reconnect every time. tn = Telnet(self.host, self.port, self.timeout) tn.write('{}\n'.format(word)) 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)
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.")
tn = Telnet(self.host, self.port, self.timeout) tn.write('{}\n'.format(word)) 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: