예제 #1
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)
## Add a command line argument
np.add_arg("i", "instance-id", "Amazon EC2 Instance ID", required=True)

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

## Use specified Instance ID
ec2_instance_id = np['i']

## Unable to connect
try:
    conn = boto.connect_ec2()
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 instance status
try:
    instance = conn.get_all_instance_status(ec2_instance_id)[0]
except:
    np.nagios_exit(
        UNKNOWN,
        "Unable to get instance %s. Is network up ? Is region configured ? (Region %s)"
        % (ec2_instance_id, conn.DefaultRegionName))

## Confioguration return messge + code
map_instance_status = {}
map_instance_status[0] = ('instance is pending (maybe starting)', UNKNOWN)
map_instance_status[16] = ('instance is running', OK)
예제 #4
0
## This is for the custom nagios module
sys.path.insert(1, '../')
from pynag.Plugins import simple as Plugin


## Create the plugin option
np = Plugin()

## Add a command line argument
np.add_arg("l","load-file", "Enter a load average file", required=None)

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

## Use a custom load average file, if specified to
if np['load-file']:
	load_file = np['load-file']
else:
	load_file = "/proc/loadavg"

if not os.path.isfile(load_file):
	np.nagios_exit("UNKNOWN", "Missing Load average file %s" % load_file)

## Get the check value
current_load = os.popen("cat %s" % load_file).readline().split()[0]

## Add the perdata
np.add_perfdata("1min", current_load)

np.check_range(current_load)
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)
## 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)
except:
  np.nagios_exit(UNKNOWN, "Unable to get elb list. Is network up ? Is region configured ? (Region %s)" % ( conn.DefaultRegionName))

## Get desired instance
instance_health = [instance for instance in instances_health if instance.instance_id == instance_id]

## If instance is not registered
if len(instance_health) == 0:
  np.nagios_exit(WARNING, "Instance %s is not registered into %s" % ( instance_id, elb_name))

## Return value
예제 #7
0
from subprocess import Popen, PIPE
from pprint import pprint

## Create the plugin option
np = Plugin()

np.add_arg('l', 'long-output', 'Allows for long multiline output', required=0, action='store_true')

# Parse the plugin options
np.activate()

p = Popen("mtr -c 4 --raw %s" % (np['host']), shell=True, stdout=PIPE, stderr=PIPE, close_fds=True)
stdout, stderr = p.communicate('through stdin to stdout')
if p.returncode > 0:
	if p.returncode == 127: # File not found, lets print path
		np.nagios_exit(UNKNOWN, "Unable to find mtr, check that it is installed")
	else:
		np.nagios_exit(UNKNOWN, "Unable to run mtr: %s" % (stderr.strip()))


mtr_output = {}
for line in stdout.split("\n"):
	if not line:
		continue
	line.strip()
	(l_type, l_id, l_data) = line.split(" ", 3)

	if mtr_output.has_key(l_id) == False:
		mtr_output[l_id] = { 'p': [] }

	if l_type == "p":
np = Plugin()

## Add a command line argument
np.add_arg("i","instance-id", "Amazon EC2 Instance ID", required=True)

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

## Use specified Instance ID
ec2_instance_id = np['i']

## Unable to connect
try:
  conn = boto.connect_ec2()
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 instance status
try:
  instance = conn.get_all_instance_status(ec2_instance_id)[0]
except:
  np.nagios_exit(UNKNOWN, "Unable to get instance %s. Is network up ? Is region configured ? (Region %s)" % ( ec2_instance_id, conn.DefaultRegionName))

## Confioguration return messge + code
map_instance_status = {}
map_instance_status[0] = ('instance is pending (maybe starting)', UNKNOWN)
map_instance_status[16] = ('instance is running', OK)
map_instance_status[32] = ('instance is shutting down', WARNING)
map_instance_status[48] = ('instance is terminated', CRITICAL)
map_instance_status[64] = ('instance is stopping', WARNING)
map_instance_status[80] = ('instance is stopped', CRITICAL)
예제 #9
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)
## Add a command line argument
np.add_arg("n", "name", "Amazon ELB name", required=True)

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

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

## 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:
    elbs = conn.get_all_load_balancers(elb_name)
except:
    np.nagios_exit(
        UNKNOWN,
        "Unable to get elb list. Is network up ? Is region configured ? (Region %s)"
        % (conn.DefaultRegionName))

# Return value
if not elbs:
    np.nagios_exit(CRITICAL, "No ELB named %s" % elb_name)
else:
예제 #11
0
        if plugin['port'] <= 0:
            raise ValueError
    except ValueError as ex:
        plugin.parser.error('Invalid port number')

# Run chrony tracking
command = [
    'chronyc', '-h', plugin['host'], '-p',
    str(plugin['port']), 'tracking'
]

try:
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)
    output = process.communicate()[0]
except OSError as ex:
    plugin.nagios_exit(Plugins.UNKNOWN, str(ex))

if process.returncode != 0:
    plugin.nagios_exit(Plugins.CRITICAL, output.rstrip())

matcher = re.search(r'^Leap status\s*:\s*(.*)$', output, flags=re.MULTILINE)
leap_status = matcher.group(1)
if leap_status == 'Not synchronised':
    plugin.nagios_exit(Plugins.CRITICAL, 'Server is not synchronised')
if leap_status == 'Unknown':
    plugin.nagios_exit(Plugins.UNKNOWN, 'Server status is unknown')

matcher = re.search(r'^System time\s*:\s*([0-9]+\.[0-9]*) seconds (slow|fast)',
                    output,
                    flags=re.MULTILINE)
offset = float(matcher.group(1))
    "numbers",
    "Numbers of desired instance running in the pool. Default will be half total number of node",
    required=False)

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

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

## 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)
except:
    np.nagios_exit(
        UNKNOWN,
        "Unable to get elb list. Is network up ? Is region configured ? (Region %s)"
        % (conn.DefaultRegionName))

number_of_instance = len(instances_health)
number_of_running_instance = 0
for instance_health in instances_health:
    if instance_health.state == 'InService':
np = Plugin()

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

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

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

## 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:
  elbs = conn.get_all_load_balancers(elb_name)
except:
  np.nagios_exit(UNKNOWN, "Unable to get elb list. Is network up ? Is region configured ? (Region %s)" % ( conn.DefaultRegionName))

# Return value
if not elbs:
  np.nagios_exit(CRITICAL, "No ELB named %s" % elb_name)
else:
  np.nagios_exit(OK, "ELB exist")

예제 #14
0
파일: check_cpu.py 프로젝트: zothar/pynag
import os, sys

## Import plugin from nagios Module
from pynag.Plugins import simple as Plugin

## Create the plugin option
np = Plugin()

## Add a command line argument
np.add_arg("l", "load-file", "Enter a load average file", required=None)

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

## Use a custom load average file, if specified to
if np['load-file']:
    load_file = np['load-file']
else:
    load_file = "/proc/loadavg"

if not os.path.isfile(load_file):
    np.nagios_exit("UNKNOWN", "Missing Load average file %s" % load_file)

## Get the check value
current_load = open(load_file).readline().split()[0]

## Add the perdata
np.add_perfdata("1min", current_load)

np.check_range(current_load)
import sys
from pydisque.client import Client
from pynag.Plugins import CRITICAL, simple as Plugin


np = Plugin(must_threshold=False)
np.activate()


try:
    client = Client()   # Client(['127.0.0.1:7711'])
    client.connect()
except:
    np.nagios_exit(
        CRITICAL,
        'Mayby disque is down.',
    )
    sys.exit(1)

class Disque(object):
    def __init__(self):
        self.__info = client.execute_command('INFO')
        self.create_properties()

    def create_properties(self):
        for k, v in self.__info.iteritems():
            self.__dict__[k] = v

disque = Disque()

info_properties = [
예제 #16
0
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)
except:
    np.nagios_exit(
        UNKNOWN,
        "Unable to get elb list. Is network up ? Is region configured ? (Region %s)"
        % (conn.DefaultRegionName))

## Get desired instance
instance_health = [
    instance for instance in instances_health
    if instance.instance_id == instance_id
## Add a command line argument
np.add_arg("n","name", "Amazon ELB name", required=True)
np.add_arg("N","numbers", "Numbers of desired instance running in the pool. Default will be half total number of node", required=False)

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

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

## 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)
except:
  np.nagios_exit(UNKNOWN, "Unable to get elb list. Is network up ? Is region configured ? (Region %s)" % ( conn.DefaultRegionName))

number_of_instance=len(instances_health)
number_of_running_instance=0
for instance_health in instances_health:
  if instance_health.state == 'InService':
    number_of_running_instance += 1

if np["numbers"] == None:
  desired_number = number_of_instance/2