当前位置: 首页>>代码示例>>Python>>正文


Python PluginHelper.exit方法代码示例

本文整理汇总了Python中pynag.Plugins.PluginHelper.exit方法的典型用法代码示例。如果您正苦于以下问题:Python PluginHelper.exit方法的具体用法?Python PluginHelper.exit怎么用?Python PluginHelper.exit使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pynag.Plugins.PluginHelper的用法示例。


在下文中一共展示了PluginHelper.exit方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
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()
开发者ID:OrgoSteph,项目名称:plugins,代码行数:27,代码来源:systemdsvc.py

示例2: testPluginHelper

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
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)
开发者ID:bnrubin,项目名称:pynag,代码行数:29,代码来源:plugintest.py

示例3: main

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
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()
开发者ID:triicst,项目名称:nagios-plugins,代码行数:51,代码来源:check_memory.py

示例4: reload

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
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()
开发者ID:arthurtiteica,项目名称:monitor-iceland,代码行数:32,代码来源:check_takktakkvolcano.py

示例5: zip

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
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)
开发者ID:rsmuc,项目名称:health_monitoring_plugins,代码行数:33,代码来源:check_snmp_ubiquiti.py

示例6: PluginHelper

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
# 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()
开发者ID:AccelerationNet,项目名称:pynag,代码行数:17,代码来源:check_stuff.py

示例7: name

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
# 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))
开发者ID:jasperGreve,项目名称:monplugs,代码行数:33,代码来源:check_interfaces_byName.py

示例8: PluginHelper

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
# 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)
开发者ID:MirrorZ,项目名称:pynag,代码行数:32,代码来源:check_load.py

示例9: monitor

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
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",
开发者ID:rsmm01,项目名称:check_snmp_raritan,代码行数:33,代码来源:check_snmp_raritan.py

示例10: dict

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]

# 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'], )
开发者ID:morgajel,项目名称:morgnagplug,代码行数:32,代码来源:check_apachestatus.py

示例11: verify_host

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
    "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()
开发者ID:rsmuc,项目名称:health_monitoring_plugins,代码行数:32,代码来源:check_snmp_lband.py

示例12: PluginHelper

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
        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?)")
开发者ID:funollet,项目名称:nagios-plugins,代码行数:33,代码来源:check_zookeeper.py

示例13: time

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
            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()
开发者ID:rsmuc,项目名称:health_monitoring_plugins,代码行数:32,代码来源:check_snmp_time2.py

示例14: len

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
        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()
开发者ID:rsmuc,项目名称:health_monitoring_plugins,代码行数:32,代码来源:check_snmp_service.py

示例15: scan_ilo

# 需要导入模块: from pynag.Plugins import PluginHelper [as 别名]
# 或者: from pynag.Plugins.PluginHelper import exit [as 别名]
    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
开发者ID:rsmuc,项目名称:health_monitoring_plugins,代码行数:32,代码来源:check_snmp_ilo4.py


注:本文中的pynag.Plugins.PluginHelper.exit方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。