예제 #1
0
파일: plugintest.py 프로젝트: bnrubin/pynag
class testPlugin(unittest.TestCase):
    def setUp(self):
        self.argv_store = sys.argv
        from pynag.Plugins import simple as Plugin
        self.np = Plugin()
        sys.stdout = StringIO()
        sys.stderr = StringIO()
    def tearDown(self):
        sys.argv = self.argv_store
        sys.stdout = original_stdout
        sys.stderr = original_stderr

    def run_expect(self, case, expected_exit, value):
        sys.argv = [sys.argv[0]] + case.split()
        self.np.activate()
        try:
            self.np.add_perfdata('fake', value, uom='fakes',
                                 warn=10, crit=20, minimum=-100, maximum=100)
            perfdata_string = self.np.perfdata_string()
            print perfdata_string
            self.assertEquals(perfdata_string, "| '%s'=%s%s;%s;%s;%s;%s" % (
                              'fake', value, 'fakes', 10, 20, -100, 100))
            self.np.add_message('OK', 'Some message')
            self.assertEquals(self.np.data['messages'][0], ['Some message'])
            self.np.check_range(value)
        except SystemExit, e:
            self.assertEquals(type(e), type(SystemExit()))
            self.assertEquals(e.code, expected_exit)
        except Exception, e:
            import traceback
            print traceback.format_exc()
            self.fail('unexpected exception: %s' % e)
예제 #2
0
def main():
    global plugin

    plugin = Plugin(must_threshold=False)
    plugin.add_arg("l",
                   "logical-volume",
                   "Comma seperated list of VG/LV, eg vg00/data,vg00/snap",
                   required=False)
    plugin.add_arg("V",
                   "volume-group",
                   "Comma seperated list of VG, eg vg00,vg01",
                   required=False)
    plugin.add_arg("a",
                   "check-all",
                   "Check all LVs",
                   required=False,
                   action="store_true")
    plugin.activate()

    lvs = plugin["logical-volume"] and plugin["logical-volume"].split(
        ",") or []
    vgs = plugin["volume-group"] and plugin["volume-group"].split(",") or []

    if not lvs and not vgs and not plugin['check-all']:
        plugin.parser.error(
            "Either logical-volume or volume-group must be specified")
    elif plugin['check-all'] and (lvs or vgs):
        plugin.parser.error(
            "Mixing check-all and logical-volume or volume-group does not make sense"
        )

    check_mirror(lvs, vgs, plugin['check-all'], plugin['host'])

    (code, message) = (plugin.check_messages(joinallstr="\n"))
    plugin.nagios_exit(code, message)
def main():
    global plugin

    plugin = Plugin(must_threshold=False)
    plugin.add_arg("l", "logical-volume",
                   "Comma seperated list of VG/LV, eg vg00/data,vg00/snap",
                   required=False)
    plugin.add_arg("V", "volume-group",
                   "Comma seperated list of VG, eg vg00,vg01",
                   required=False)
    plugin.add_arg("a", "check-all", "Check all LVs", required=False,
                   action="store_true")
    plugin.activate()

    lvs = plugin["logical-volume"] and plugin["logical-volume"].split(
        ",") or []
    vgs = plugin["volume-group"] and plugin["volume-group"].split(",") or []

    if not lvs and not vgs and not plugin['check-all']:
        plugin.parser.error(
            "Either logical-volume or volume-group must be specified")
    elif plugin['check-all'] and ( lvs or vgs ):
        plugin.parser.error(
            "Mixing check-all and logical-volume or volume-group does not make sense")

    check_mirror(lvs, vgs, plugin['check-all'], plugin['host'])

    (code, message) = (plugin.check_messages(joinallstr="\n"))
    plugin.nagios_exit(code, message)
예제 #4
0
class testPluginNoThreshold(unittest.TestCase):
    def setUp(self):
        self.argv_store = sys.argv
        from pynag.Plugins import simple as Plugin
        self.np = Plugin(must_threshold=False)
    def tearDown(self):
        sys.argv = self.argv_store
    def run_expect(self, case, expected_exit, value):
        sys.argv = [sys.argv[0]] + case.split()
        self.np.activate()
        try:
            self.np.check_range(value)
        except SystemExit, e:
            self.assertEquals(type(e), type(SystemExit()))
            self.assertEquals(e.code, expected_exit)
        except Exception, e:
            self.fail('unexpected exception: %s' % e)
예제 #5
0
class PluginNoThreshold(unittest.TestCase):

    def setUp(self):
        self.argv_store = sys.argv
        from pynag.Plugins import simple as Plugin
        self.np = Plugin(must_threshold=False)
        sys.stdout = StringIO()

    def tearDown(self):
        sys.argv = self.argv_store
        sys.stdout = original_stdout

    def run_expect(self, case, expected_exit, value):
        sys.argv = [sys.argv[0]] + case.split()
        self.np.activate()
        try:
            self.np.check_range(value)
        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')

    # All tests return OK since thresholds are not required
    def test_number_1(self):
        case = ''
        self.run_expect(case, 0, -23)

    def test_number_2(self):
        case = ''
        self.run_expect(case, 0, 0)

    def test_number_3(self):
        case = ''
        self.run_expect(case, 0, 2)

    def test_number_4(self):
        case = ''
        self.run_expect(case, 0, 10)

    def test_number_5(self):
        case = ''
        self.run_expect(case, 0, 15)
예제 #6
0
class PluginParams(unittest.TestCase):

    def setUp(self):
        self.argv_store = sys.argv
        from pynag.Plugins import simple as Plugin
        self.np = Plugin(must_threshold=False)
        sys.stdout = StringIO()

    def tearDown(self):
        sys.argv = [sys.argv[0]]
        sys.stdout = original_stdout

    def create_params(self, *args):
        sys.argv.extend(args)

    def test_default_verbose(self):
        #sys.argv = [sys.argv[0]] + ['-v', '10']
        self.create_params('-v', '10')
        self.np.activate()
        self.assertEquals(self.np.data['verbosity'], 0)

    def test_verbose(self):
        self.create_params('-v', '3')
        self.np.activate()
        self.assertEquals(self.np.data['verbosity'], 3)

    def test_set_hostname(self):
        self.create_params('-H', 'testhost.example.com')
        self.np.activate()
        self.assertEquals(self.np.data['host'], 'testhost.example.com')

    def test_set_timeout(self):
        self.create_params('-t', '100')
        self.np.activate()
        self.assertEquals(self.np.data['timeout'], '100')

    def test_default_timeout(self):
        self.np.activate()
        self.assertEquals(self.np.data['timeout'], None)

    def test_shortname(self):
        from pynag.Plugins import simple as Plugin
        np = Plugin(shortname='testcase')
        self.assertEquals(np.data['shortname'], 'testcase')
예제 #7
0
class PluginParams(unittest.TestCase):

    def setUp(self):
        self.argv_store = sys.argv
        from pynag.Plugins import simple as Plugin
        self.np = Plugin(must_threshold=False)
        sys.stdout = StringIO()

    def tearDown(self):
        sys.argv = [sys.argv[0]]
        sys.stdout = original_stdout

    def create_params(self, *args):
        sys.argv.extend(args)

    def test_default_verbose(self):
        #sys.argv = [sys.argv[0]] + ['-v', '10']
        self.create_params('-v', '10')
        self.np.activate()
        self.assertEquals(self.np.data['verbosity'], 0)

    def test_verbose(self):
        self.create_params('-v', '3')
        self.np.activate()
        self.assertEquals(self.np.data['verbosity'], 3)

    def test_set_hostname(self):
        self.create_params('-H', 'testhost.example.com')
        self.np.activate()
        self.assertEquals(self.np.data['host'], 'testhost.example.com')

    def test_set_timeout(self):
        self.create_params('-t', '100')
        self.np.activate()
        self.assertEquals(self.np.data['timeout'], '100')

    def test_default_timeout(self):
        self.np.activate()
        self.assertEquals(self.np.data['timeout'], None)

    def test_shortname(self):
        from pynag.Plugins import simple as Plugin
        np = Plugin(shortname='testcase')
        self.assertEquals(np.data['shortname'], 'testcase')
예제 #8
0
#! /usr/bin/python

from pynag.Plugins import WARNING, CRITICAL, OK, UNKNOWN, simple as Plugin
import boto

## Create the plugin option
np = Plugin()

## Add a command line argument
np.add_arg("n", "name", "Amazon ELB name", required=True)
np.add_arg("i", "instance", "Amazon EC2 instance ID", required=True)

## This starts the actual plugin activation
np.activate()

## Use specified ELB name
elb_name = np['name']
instance_id = np['instance']

## Unable to connect
try:
    conn = boto.connect_elb()
except boto.exception.NoAuthHandlerFound:
    np.nagios_exit(
        UNKNOWN,
        "Unable to log into AWS. Please Check your /etc/boto.cfg file or AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variable."
    )

## Unable to get elbs
try:
    instances_health = conn.describe_instance_health(elb_name)
예제 #9
0
#Create the plugin option
np = Plugin()

#Configure additional command line arguments
np.add_arg("R", "ssh_host", "Ssh remote machine name to connect to", required=True)
np.add_arg("P", "ssh_password", "Ssh romote host password", required=None)
np.add_arg("U", "ssh_username", "Ssh remote username", required=None)
np.add_arg("s", "ssh_port", "Ssh remote host port (default: 22)", required=None)
np.add_arg("l", "query_address", "Machine name to lookup", required=True)
np.add_arg("p", "port", "DNS Server port number (default: 53)", required=None)
np.add_arg("T", "record_type", "Record type to lookup (default: A)", required=None)
np.add_arg("a", "expected_address", "An address expected to be in the answer section. If not set, uses whatever was in query address", required=None)
np.add_arg("A", "dig-arguments", "Pass the STRING as argument(s) to dig", required=None)

#Plugin activation
np.activate()

#Main script logic 8-)
CMD_ITEM_1 = "dig"
CMD_ITEM_2 = " "             #Here we should insert a servername/ip
CMD_ITEM_3 = " "        #Here should be the port for a server/ip (default: 53)
CMD_ITEM_4 = " "             #Machine name to lookup
CMD_ITEM_5 = " "            #Record type
CMD_ITEM_6 = " "             #Dig additional args

#Data gathering
if np['query_address']:
    CMD_ITEM_4 = np['query_address']

if  (np['host'] and np['port']):
    CMD_ITEM_2 = "@"+np['host']
def main():
    global np
    np = Plugin(must_threshold=False)

    np.add_arg('w', 
               'warning', 
               'Warn when X days until certificate expires', 
               required=None)
    np.add_arg('c', 
               'critical', 
               'Critical when X days until certificate expires', 
               required=None)

    np.activate()

    if np['warning'] is None:
        np['warning'] = "14"
    if np['critical'] is None:
        np['critical'] = "2"

    for t in ['warning', 'critical']:
        if np[t] and np[t].isdigit() is False:
            print "%s threshold must be a positive number" % t.capitalize()
            sys.exit(3)

    certs = getcert_list()

    for cert in certs:
        if cert['stuck'] != "no":
            np.add_message(
                   WARNING, 
                   "Certificate %s from certdb %s is stuck=%s" % (
                       cert['certificate']['nickname'], 
                       cert['certificate']['location'],
                       cert['stuck']))

        expires_diff = cert['expires'] - datetime.datetime.now()
        if expires_diff.days < 0:
            np.add_message(
                   CRITICAL,
                   "Certificate %s from certdb %s has EXPIRED %i days ago" % (
                       cert['certificate']['nickname'], 
                       cert['certificate']['location'],
                       expires_diff.days*-1))

        elif expires_diff.days < int(np['critical']):
            np.add_message(
                   CRITICAL,
                   "Certificate %s from certdb %s expires in %i days" % (
                       cert['certificate']['nickname'], 
                       cert['certificate']['location'],
                       expires_diff.days))

        elif expires_diff.days < int(np['warning']):
            np.add_message(
                   WARNING,
                   "Certificate %s from certdb %s expires in %i days" % (
                       cert['certificate']['nickname'], 
                       cert['certificate']['location'],
                       expires_diff.days))

        else:
            np.add_message(
                   OK,
                   "Certificate %s from certdb %s expires in %i days" % (
                       cert['certificate']['nickname'], 
                       cert['certificate']['location'],
                       expires_diff.days))

    code, messages = np.check_messages(joinallstr="\n")
    np.nagios_exit(code, messages)
예제 #11
0
파일: proc.py 프로젝트: r00tgms/GMSterminal
def main():
    global np
    global tmpdir

    # new pynag.Plugin
    np = Plugin(must_threshold=False)

    # Arguments
    np.add_arg('f',
               'file',
               'Remote file, space seperate multiple files',
               required=False)
    np.add_arg('w',
               'warning',
               'Warn if tftp downloads take longer',
               required=False)
    np.add_arg('c',
               'critical',
               'Critical if tftp downloads take longer',
               required=False)
    np.add_arg('l',
               'longoutput',
               'Each file broken up into a new line for readability',
               required=False,
               action="store_true")

    # Activate
    np.activate()

    if np['host'] == "":
        np.nagios_exit(UNKNOWN, "Hostname is required")

    tmpdir = mktmpdir()

    end_time = time.time() + int(np['timeout'] or 20)

    # data.txt add manually contient list of file that we will check
    #  dirname = os.path.join('data', 'tftplist.txt')
    dir = os.path.dirname(os.path.realpath(__file__))
    with open(dir + '/data.txt', 'r') as myfile:
        files = myfile.read().replace('\n', '')


# creat list of ips #files = np['file'].split()

    with open(dir + '/ips.txt', 'r') as myips:
        ips = myips.read().replace('\n', '')

    # Loop through the files
    for ip in ips:
        for file in files:
            file_start_time = time.time()
            try:
                size = tftp_get(ip, file, timeout=(end_time - time.time()))
                file_end_time = time.time()
                run_time = time.time() - file_start_time

                if size is not False:
                    if np['critical'] and run_time >= int(np['critical']):
                        stat = CRITICAL
                    elif np['warning'] and run_time >= int(np['warning']):
                        stat = WARNING
                    else:
                        stat = OK
                    np.add_message(
                        stat, "tftp://%s/%s got %iB in %.2f secs" %
                        (np['host'], file, size,
                         (file_end_time - file_start_time)))

                    np.add_perfdata("%s_size" % (file), size)

                    np.add_perfdata("%s_fetch" % (file),
                                    (file_end_time - file_start_time))

            except Exception, e:
                np.nagios_exit(UNKNOWN, e)
예제 #12
0
# see <http://www.gnu.org/licenses/>.

import re
import subprocess

from pynag import Plugins
from pynag.Plugins import simple as Plugin

DEFAULT_CHRONYD_PORT = 323

plugin = Plugin()

# Specify arguments to the plugin
plugin.add_arg('p', 'port', 'Chrony UDP port', required=None)

plugin.activate()

if plugin['critical'] <= plugin['warning']:
    plugin.parser.error(
        'Critical level cannot be lesser than or equal to warning')

if plugin['host'] is None:
    plugin['host'] = 'localhost'

if plugin['port'] is None:
    plugin['port'] = DEFAULT_CHRONYD_PORT
else:
    try:
        plugin['port'] = float(plugin['port'])
        if plugin['port'] <= 0:
            raise ValueError
예제 #13
0
class Plugin(unittest.TestCase):

    def setUp(self):
        self.argv_store = sys.argv
        from pynag.Plugins import simple as Plugin
        self.np = Plugin()
        sys.stdout = StringIO()
        sys.stderr = StringIO()

    def tearDown(self):
        sys.argv = self.argv_store
        sys.stdout = original_stdout
        sys.stderr = original_stderr

    def run_expect(self, case, expected_exit, value):
        sys.argv = [sys.argv[0]] + case.split()
        self.np.activate()
        try:
            self.np.add_perfdata('fake', value, uom='fakes',
                                 warn=10, crit=20, minimum=-100, maximum=100)
            perfdata_string = self.np.perfdata_string()
            print(perfdata_string)
            self.assertEquals(perfdata_string, "| '%s'=%s%s;%s;%s;%s;%s" % (
                              'fake', value, 'fakes', 10, 20, -100, 100))
            self.np.add_message('OK', 'Some message')
            self.assertEquals(self.np.data['messages'][0], ['Some message'])
            self.np.check_range(value)
        except SystemExit as e:
            self.assertEquals(type(e), type(SystemExit()))
            self.assertEquals(e.code, expected_exit)
        except Exception as e:
            import traceback
            print(traceback.format_exc())
            self.fail('unexpected exception: %s' % e)
        else:
            self.fail('SystemExit exception expected')

    # Throws SystemExit, required parameter not set when activating
    def test_add_arg_req_missing(self):
        self.np.add_arg('F', 'fakedata',
                        'fake data to test thresholds', required=True)
        self.assertRaises(SystemExit, self.np.activate)

    def test_add_arg_req(self):
        self.np.add_arg('F', 'fakedata',
                        'fake data to test thresholds', required=True)
        sys.argv = [sys.argv[0]] + '-F 100 -w 1 -c 2'.split()
        self.np.activate()

    def test_add_arg(self):
        self.np.add_arg('F', 'fakedata',
                        'fake data to test thresholds', required=False)
        sys.argv = [sys.argv[0]] + '-w 1 -c 2'.split()
        self.np.activate()

    def test_codestring_to_int(self):
        code = self.np.code_string2int('OK')
        self.assertEquals(code, 0, "OK did not map to 0")

        code = self.np.code_string2int('WARNING')
        self.assertEquals(code, 1, "WARNING did not map to 1")

        code = self.np.code_string2int('CRITICAL')
        self.assertEquals(code, 2, "CRITICAL did not map to 2")

        code = self.np.code_string2int('UNKNOWN')
        self.assertEquals(code, 3, "UNKNOWN did not map to 3")

    # 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 = '-w 10 -c 20'
        self.run_expect(case, 2, -23)

    def test_number_2(self):
        case = '-w 10 -c 20'
        self.run_expect(case, 0, 3)

    def test_number_3(self):
        case = '-w 10 -c 20'
        self.run_expect(case, 1, 13)

    def test_number_4(self):
        case = '-w 10 -c 20'
        self.run_expect(case, 2, 23)

    # Same as above. Negative "stuff" is OK
    def test_number_5(self):
        case = '-w ~:10 -c ~:20'
        self.run_expect(case, 0, -23)

    def test_number_6(self):
        case = '-w ~:10 -c ~:20'
        self.run_expect(case, 0, 3)

    def test_number_7(self):
        case = '-w ~:10 -c ~:20'
        self.run_expect(case, 1, 13)

    def test_number_8(self):
        case = '-w ~:10 -c ~:20'
        self.run_expect(case, 2, 23)

    # 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 = '-w 10: -c 20'
        self.run_expect(case, 2, -23)

    def test_number_10(self):
        case = '-w 10: -c 20'
        self.run_expect(case, 1, 3)

    def test_number_11(self):
        case = '-w 10: -c 20'
        self.run_expect(case, 0, 13)

    def test_number_12(self):
        case = '-w 10: -c 20'
        self.run_expect(case, 2, 23)

    # Critical if "stuff" is less than 1
    def test_number_13(self):
        case = '-c 1:'
        self.run_expect(case, 2, -23)

    def test_number_14(self):
        case = '-c 1:'
        self.run_expect(case, 2, 0)

    def test_number_15(self):
        case = '-c 1:'
        self.run_expect(case, 0, 13)

    def test_number_16(self):
        case = '-c 1:'
        self.run_expect(case, 0, 23)

    # 1-9 is warning, negative or above 10 is critical
    def test_number_17(self):
        case = '-w ~:0 -c 10'
        self.run_expect(case, 2, -23)

    def test_number_18(self):
        case = '-w ~:0 -c 10'
        self.run_expect(case, 0, 0)

    def test_number_19(self):
        case = '-w ~:0 -c 10'
        self.run_expect(case, 1, 7)

    def test_number_20(self):
        case = '-w ~:0 -c 10'
        self.run_expect(case, 2, 23)

    # The only noncritical range is 5:6
    def test_number_21(self):
        case = '-c 5:6'
        self.run_expect(case, 2, -23)

    def test_number_22(self):
        case = '-c 5:6'
        self.run_expect(case, 2, 0)

    def test_number_23(self):
        case = '-c 5:6'
        self.run_expect(case, 2, 2)

    def test_number_24(self):
        case = '-c 5:6'
        self.run_expect(case, 0, 5)

    def test_number_25(self):
        case = '-c 5:6'
        self.run_expect(case, 0, 6)

    # Critical if "stuff" is 10 to 20
    def test_number_26(self):
        case = '-c @10:20'
        self.run_expect(case, 0, -23)

    def test_number_27(self):
        case = '-c @10:20'
        self.run_expect(case, 0, 0)

    def test_number_28(self):
        case = '-c @10:20'
        self.run_expect(case, 0, 2)

    def test_number_29(self):
        case = '-c @10:20'
        self.run_expect(case, 2, 10)

    def test_number_30(self):
        case = '-c @10:20'
        self.run_expect(case, 2, 15)

    def test_number_31(self):
        case = '-c @10:20'
        self.run_expect(case, 2, 20)

    def test_number_32(self):
        case = '-c @10:20'
        self.run_expect(case, 0, 23)