Beispiel #1
0
def deviceIssuesReport():
    '''
    This method sorts through the data and prints it out in
    .csv format. There are several other fields one might be
    interested in here, but here are a few as an example.
    '''
    print('Device, Device Class, ProdState, Clear, Debug, Info '\
          'Warning, Error, Critical')
    dr = zenApiLib.zenConnector(routerName = 'DashboardRouter')
    report_data = dr.callMethod('getDeviceIssues')
    if report_data.get('result', {}).get('success', False) is False:
        raise Exception('API call returned unsucessful result.\n%s' % report_data)
    for entry in report_data['result']['data']:
        device = entry['device']
        deviceClass = entry['deviceClass']['uid']
        deviceClass = deviceClass.replace('/zport/dmd/Devices', '')
        prodState = entry['productionStateLabel']
        events = entry['events']
        clear = events['clear']['count']
        debug = events['debug']['count']
        info = events['info']['count']
        warning = events['warning']['count']
        error = events['error']['count']
        critical = events['critical']['count']
        print('%s, %s, %s, %s, %s, %s, %s, %s, %s' % (device,
                                                      deviceClass,
                                                      prodState,
                                                      clear,
                                                      debug,
                                                      info,
                                                      warning,
                                                      error,
                                                      critical))
Beispiel #2
0
def addProcessFromFile():
    '''
    This makes the API call and returns data
    '''
    processRouter = zenApiLib.zenConnector(routerName='ProcessRouter')
    file = open("Processlist.txt", "r")
    for line in file:
        words = line.strip().split()
        if len(words) == 2:
            (org, process) = words
            myroot = "/".join((PROCESS_ROOT, org, 'osProcessClasses'))
            path = ''
            for node in org.split('/'):
                processRouter.callMethod('addNode',
                                         type="oroganizer",
                                         id=node,
                                         contextUid=PROCESS_ROOT + path)
                path = '/'.join((path, node))
        else:
            process = words[0]
            myroot = PROCESS_CLASS_ROOT
        processRouter.callMethod('addNode',
                                 type="class",
                                 id=process,
                                 contextUid=myroot)
        includeRegex = '^[^ ]*{}[^ /]*( |$)'.format(process)
        replaceRegex = '^([^ ]*{}[^ /]*)( |$)'.format(process)
        processRouter.callMethod('setInfo',
                                 uid="/".join((myroot, process)),
                                 includeRegex=includeRegex,
                                 replaceRegex=replaceRegex,
                                 replacement='\\1')
Beispiel #3
0
def setWinServiceMonitored():
    '''
    This makes the API call and returns data
    '''
    serviceRouter = zenApiLib.zenConnector(routerName='ServiceRouter')
    file = open("servicelist.txt", "r")
    for service in file:
        serviceRouter.callMethod('setInfo', uid=(SERVICE_ROOT + '/' + service.strip()), zMonitor={"isAcquired": False, "localValue": True}, monitoredStartModes='Manual')
Beispiel #4
0
def getJobs():
    '''
    This makes the API call and returns data
    '''
    dr = zenApiLib.zenConnector(routerName = router)
    response = dr.callMethod(method, **data)
    if response.get('result', {}).get('success', False) is False:
        raise Exception('API call returned unsucessful result.\n%s' % response)
    return response['result']
def addProcessFromFile():
    '''
    This makes the API call and returns data
    '''
    processRouter = zenApiLib.zenConnector(routerName='ProcessRouter')
    file = open("Processlist.txt", "r")
    for process in file:
        processRouter.callMethod('addNode', type="class", id=process.strip(), contextUid="/zport/dmd/Processes")
        processRouter.callMethod('setInfo', uid=(PROCESS_ROOT + '/' + process.strip()), includeRegex=('^[^ ]*' + process.strip() + '[^ /]*( |$)'))
Beispiel #6
0
def addDevice(data):
    '''
    This makes the API call and returns the result
    '''
    dr = zenApiLib.zenConnector(routerName=router)
    response = dr.callMethod(method, **data)
    if response.get('result', {}).get('success', False) is False:
        raise Exception('API call returned unsucessful result.\n%s' % response)
    return response['result']['new_jobs'][0]['uuid']
Beispiel #7
0
 def __init__(self, query):
     self.uuid = None
     self.results = []
     self.log = logging.getLogger('zenApiDeviceRouterHelper.ZenDeviceUuidFinder')
     deviceAPI = zenApiLib.zenConnector(routerName = 'DeviceRouter')
     apiResults = deviceAPI.callMethod('getDeviceUuidsByName', query = query)
     for resp in apiResults:
         if resp['result']['sucess']:
             self.results += resp['result']['data']
         else:
             self.log.error('Non-sucessful result returned: %s' % resp)
     self.count = len(self.results)
Beispiel #8
0
 def __init__(self, query):
     self.uuid = None
     self.results = []
     self.log = logging.getLogger('zenApiDeviceRouterHelper.ZenDeviceUuidFinder')
     deviceAPI = zenApiLib.zenConnector(routerName = 'DeviceRouter')
     apiResults = deviceAPI.callMethod('getDeviceUuidsByName', query = query)
     if apiResults.get('result', {}).get('success', False) is False:
         raise Exception('Device query failed')
     if apiResults['result']['data']:
         self.results = apiResults['result']['data']
     else:
         self.log.error('Non-sucessful result returned: %s' % resp)
     self.count = len(self.results)
Beispiel #9
0
 def __init__(self, name=None, ip=None):
     self.router = 'DeviceRouter'
     self.method = 'getDevices'
     self.params = {}
     if name is not None:
         self.params['name'] = name
     if ip is not None:
         self.params['ipAddress'] = ip
     self.data = {'params': self.params}
     self.api_call = zenApiLib.zenConnector()
     self.api_call.setRouter(self.router)
     self.response_json = self.api_call.callMethod(self.method, **self.data)
     self.count = len(self.response_json['result']['devices'])
Beispiel #10
0
def _initIOObject(argValue, name, log):
    if 'file:' in argValue:
        filename = argValue.split(':')[1]
        if name == "Source":
            log.warn('"-t" command parameter does not apply when source is a file')
            ioObject = json.load(open(filename, 'r'))
            count('Total objects in "{}" Source file'.format(filename), len(ioObject))
        elif name == "Destination":
            ioObject = open(filename, 'w')
    else:
        try:
            ioObject = zenApiLib.zenConnector(section=argValue)
        except Exception as e:
            log.error('Issue communicating with %s Instance API\n%r', name, e)
            sys.exit(1)
    return ioObject
Beispiel #11
0
def deviceReport():
    ''''
    This sorts through the data and displays results in a
    .csv format. There are numerous other fields that can
    be displayed here, but here are a few as an example.
    '''
    print('Name, IP Address, UID, ProdState, Collector, Location')
    dr = zenApiLib.zenConnector(routerName=router)
    for device_resp in dr.pagingMethodCall(method, **data):
        if device_resp.get('result', {}).get('success', False) is False:
            raise Exception('API call returned unsucessful result.\n%s' %
                            device_resp)
        for dev in device_resp['result']['devices']:
            try:
                location = dev['location']['uid']
            except (KeyError, TypeError):
                location = ''
            print('%s, %s, %s, %s, %s, %s' %
                  (dev['name'], dev['ipAddressString'], dev['uid'],
                   dev['productionState'], dev['collector'], location))
Beispiel #12
0
#####################################################
# This script is a basic example of how to remove a   #
# device into Zenoss Resource Manager using the     #
# Zenoss JSON API and the Zenoss RM API Library    #
#####################################################

import sys
import logging
import zenApiLib
from zenApiDeviceRouterHelper import ZenDeviceUidFinder

device_id = sys.argv[1]

response = ZenDeviceUidFinder(name=device_id)

if response.getCount() == 1:
    device_uid = response.getFirstUid()
else:
    print 'Found %s devices.' % (response.getCount())
    sys.exit(1)

dr = zenApiLib.zenConnector(routerName='DeviceRouter')

delete_response = dr.callMethod('removeDevices',
                                uids=device_uid,
                                hashcheck="",
                                action="delete")

if delete_response['result']['success'] == True:
    print 'Successfully deleted device: %s' % (device_uid)
Beispiel #13
0
#!/usr/bin/env python
################################################################
# This was written by Adam McCurdy during GalaxZ18 as an       #
# example of how to remove old maintenance windows from a      #
# specific device                                              #
################################################################
from __future__ import print_function
import zenApiLib
from time import time

dr = zenApiLib.zenConnector(routerName='DeviceManagementRouter')
response = dr.callMethod(
    'getMaintWindows',
    uid='/zport/dmd/Devices/Discovered/devices/python_device')


def delete_maint_window(mw_uid, mw_id):
    del_response = dr.callMethod('deleteMaintWindow', uid=mw_uid, id=mw_id)
    return del_response['result']['success']


curr_time = time()

for mwindow in response['result']['data']:
    if mwindow['repeat'] == 'Never':
        time_to_delete = curr_time - 86400
        if mwindow['start'] < time_to_delete:
            del_resp = delete_maint_window(mwindow['uid'], mwindow['id'])
            print(del_resp)
Beispiel #14
0

def eventClasses(evtClsUid):
    '''
    Recursively get the event classes from event class uid (evtClsUid).
    API caller, without error check since 'success' field not returned.
    Will print event class transform.
    '''
    rsp = api.callMethod('asyncGetTree', id=evtClsUid)
    evtClsTree = rsp.get('result', [])
    for evtCls in evtClsTree:
        #
        check4transform(evtCls)
        #
        if evtCls['leaf'] == False:
            #Strangely some 'branches' (not a leaf) have children defined
            #while some do not, but have count > 0. Hence the logic below.
            if evtCls.get('children', []):
                for evtClsChidren in evtCls.get('children', []):
                    check4transform(evtClsChidren)
                    eventClasses(evtClsChidren['uid'])
            elif evtCls.get("text", {}).get("count", 0):
                eventClasses(evtCls['uid'])


if __name__ == '__main__':
    api = zenApiLib.zenConnector(routerName='EventClassesRouter')
    api.config['timeout'] = 30
    mappings('/zport/dmd/Events')
    eventClasses('/zport/dmd/Events')
Beispiel #15
0
#!/usr/bin/env python

# stdlib Imports
import json
from sys import exit
import os
from urlparse import urlparse
import zenApiLib

zenAPI = zenApiLib.zenConnector(section = 'default')
zenInstance = urlparse(zenAPI.config['url']).hostname


def ServiceRouter(sMethod, dData={}):
    zenAPI.setRouter('ServiceRouter')
    respData = zenAPI.callMethod(sMethod, **dData)
    if not respData['result']['success']:
        print "ERROR: ServiceRouter %s method call non-successful" % sMethod
        print respData
        exit(1)
    if 'services' in respData['result']:
        return respData['result']['services']
    elif 'data' in respData['result']:
        return respData['result']['data']
    else:
        return None
    

def export2File(svcUid):
    exportPath = './export_%s' % zenInstance
    if not os.path.exists(exportPath):
Beispiel #16
0
    with open(filePath, 'w') as fp:
        json.dump(data, fp)


def sendEvent(**evtFields):
    evtResp = evtRouter.callMethod('add_event', **evtFields)
    if not evtResp['result']['success']:
        log.warn("sendEvent - nonSucessful results\n%s" % evtResp)


if __name__ == '__main__':
    args = buildArgs()
    log = log2stdout(args.loglevel)
    devMaintHistory = getHistory()
    thisRunDevicesInMaint = []
    devRouter = zenApiLib.zenConnector(section=args.config,
                                       routerName='DeviceRouter')
    evtRouter = zenApiLib.zenConnector(section=args.config,
                                       routerName='EventsRouter')

    # Stage1: loop through all devices in ZenossRM w/ ProdState Maintenance(300)
    devInMaint = devRouter.pagingMethodCall('getDevices',
                                            keys=["productionState", "id"],
                                            params={"productionState": [300]},
                                            limit=50)
    for apiResp in devInMaint:
        if not apiResp['result']['success']:
            log.warn("Steag1 - nonSucessful results 'getDevices':\n%s" %
                     apiResp)
            sys.exit(1)
        else:
            for dev in apiResp['result']['devices']:
Beispiel #17
0
from __future__ import print_function
import sys
import zenApiLib
from zenApiDeviceRouterHelper import ZenDeviceUidFinder

device_id = sys.argv[1]

response = ZenDeviceUidFinder(name=device_id)

if response.getCount() == 1:
    device_uid = response.getFirstUid()
else:
    print('Found %s devices.' % (response.getCount()))
    sys.exit(1)

pr = zenApiLib.zenConnector(routerName='PropertiesRouter')

delete_response = pr.callMethod('deleteZenProperty',
                                zProperty='zSnmpEngineId',
                                uid=device_uid)

if delete_response['result']['success'] == True:
    print('Deleted EngineID on %s' % (device_uid))
else:
    print('Unable to delete EngineID on %s' % (device_uid))
    sys.exit(1)

dr = zenApiLib.zenConnector(routerName='DeviceRouter')

remodel_response = dr.callMethod('remodel', deviceUid=device_uid)
Beispiel #18
0
    else:
        log.info('Successfully set threshold {} state to {}\n{}'.format(
            uid, enable, pformat(apiRawResult)))

    return apiRawResult['result']['data']


if __name__ == '__main__':
    logging.basicConfig(
        format='%(asctime)s %(levelname)s %(name)s: %(message)s')
    args = vars(buildArgs())
    logging.getLogger().setLevel(args['loglevel'])
    log = logging.getLogger(__file__)
    log.setLevel(args['loglevel'])
    api = zenApiLib.zenConnector(routerName='TemplateRouter',
                                 cfgFilePath=args['configFilePath'],
                                 section=args['configSection'],
                                 loglevel=args['loglevel'])
    if api.config['timeout'] < 30:
        api.config['timeout'] = 30
    rOut = sys.stdout

    # Specified device class must start with /
    if not args['devClass'].startswith('/'):
        log.error('If specified, device class must start with a "/"')
        sys.exit(1)

    # Try to find the specified template
    targetedTemplates = getDeviceClassTemplates('Devices' + args['devClass'])

    if len(targetedTemplates) == 0:
        # Specified template couldn't be found
def getDevices():
    dr = zenApiLib.zenConnector(routerName='DeviceRouter')
    resp = dr.callMethod('getDevices')
    devices = resp['result']['devices']
    return devices
Beispiel #20
0
#!/usr/bin/env python
from __future__ import print_function

import zenApiLib

if __name__ == '__main__':
    zenApi = zenApiLib.zenConnector()
    zenApi.setRouter('ZenPackRouter')
    apiResp = zenApi.callMethod('getZenPackMetaData')
    for zpKey in sorted(apiResp['result']['data']):
        zpMeta = apiResp['result']['data'][zpKey]
        print(zpMeta['name'], zpMeta['version']) 
Beispiel #21
0
    log = logging.getLogger(__file__)
    log.setLevel(args['loglevel'])
    if args['outFileName']:
        rOut = open(args['outFileName'], 'w')
    else:
        rOut = sys.stdout

    return log, rOut


def buildArgs():
    parser = getDefaultScriptArgParser()
    # Change default logging value. Logging arg is position 1
    parser._actions[1].default = 20
    return parser.parse_args()


if __name__ == '__main__':
    args = vars(buildArgs())
    log, rOut = initScriptEnv(args)

    apiSearchRouter = zenApiLib.zenConnector(
        section=args['configSection'],
        cfgFilePath=args['configFilePath'],
        routerName='SearchRouter')
    apiResponse = apiSearchRouter.callMethod('getCategoryCounts', query='*')
    if apiResponse['result'].get('total'):
        log.info(pformat(apiResponse['result']['results']))
        log.info('Total: %s', apiResponse['result']['total'])
    else:
        log.error('Issue making API call, %r', apiResponse)
Beispiel #22
0
 def __init__(self):
     self.api = zenApiLib.zenConnector()
Beispiel #23
0
    echo "Uncaught Exception: $$($$_.exception.message)";
    $$fail = $$True;
} if ($$fail -ne $$True) {
    $$ci = Get-ChildItem ${here/windowsRecursiveSwitch} "${here/directoryPath}\\\*" ${here/windowsFilterOrIncludeSwitch} "${here/filenameMatch}";
    $$mo = $$ci | Measure-Object -Property length -Sum;
    $$numFiles = $$mo | Select-Object -expandProperty Count;
    if ($$numFiles -gt 0) {
        $$fileSize = $$mo | Select-Object -expandProperty Sum;
        $$now = (Get-Date);
        $$oldestFileAge = ($$now - ($$ci | sort LastWriteTime -Descending | select -last 1 | Select-Object -expandProperty LastWriteTime)).TotalSeconds;
        $$newestFileAge = ($$now - ($$ci | sort LastWriteTime | select -last 1 | Select-Object -expandProperty LastWriteTime)).TotalSeconds;
        "$$numFiles,$$fileSize,$$oldestFileAge,$$newestFileAge";
    } else {
        "0,0,0,0";
    }"""
templateRouter = zenApiLib.zenConnector(routerName='TemplateRouter')
deviceRouter = zenApiLib.zenConnector(routerName='DeviceRouter')

def getDeviceList():
    device_resp = deviceRouter.callMethod('getDeviceUids', uid='/zport/dmd/Devices/Server/Microsoft/Windows')
    deviceList = device_resp['result']['devices']
    return deviceList

def bulkUpdateTemplates():
    deviceList = getDeviceList()
    for dev in deviceList:
       directoryMonitorComponents = deviceRouter.callMethod('getComponents', uid=dev, meta_type="DirectoryMonitor")
       # added a try/except here to account for devices taht didn't have directory monitor components, should be more graceful here. 
       try: 
           dm_components = directoryMonitorComponents['result']['data'][0]['uid']
       except IndexError: 
Beispiel #24
0
    return parser.parse_args()


if __name__ == '__main__':
    logging.basicConfig(
        format='%(asctime)s %(levelname)s %(name)s: %(message)s')
    logging.getLogger().setLevel(logging.ERROR)
    args = vars(buildArgs())
    log = logging.getLogger(__file__)
    log.setLevel(args['loglevel'])
    if args['outFileName']:
        rOut = open(args['outFileName'], 'w')
    else:
        rOut = sys.stdout
    api = zenApiLib.zenConnector(cfgFilePath=args['configFilePath'],
                                 section=args['configSection'],
                                 loglevel=args['loglevel'])
    api.setRouter('DeviceRouter')
    if args['dontMoveGraphData']:
        retainData = False
    else:
        retainData = True

    # Rename specified device
    deviceName = args['deviceName']
    newDeviceName = args['newDeviceName']
    results = ZenDeviceUidFinder(name=deviceName)
    if results.getCount() != 1:
        print >> sys.stderr, 'Skipping "{}", found {} devices.'.format(
            deviceName, results.getCount())
        sys.exit()
Beispiel #25
0
 def __init__(self, debug=False):
     """
     Initialize the API connection, log in, and store authentication cookie
     """
     self.api = zenApiLib.zenConnector(section = 'default', routerName = 'ImpactRouter')
    return parser.parse_args()


if __name__ == '__main__':
    args = vars(buildArgs())
    logging.basicConfig(
        format='%(asctime)s %(levelname)s %(name)s: %(message)s')
    logging.getLogger().setLevel(args['loglevel'])
    log = logging.getLogger(__file__)
    log.setLevel(args['loglevel'])
    if args['outFileName']:
        rOut = open(args['outFileName'], 'w')
    else:
        rOut = sys.stdout
    api = zenApiLib.zenConnector(routerName='DeviceDumpLoadRouter',
                                 cfgFilePath=args['configFilePath'],
                                 section=args['configSection'],
                                 loglevel=args['loglevel'])
    api.config[
        'timeout'] = 600  # Override API timeout, zen batch dump can take a long time to return data
    # workaround for argparser, 'append' will add to default value instead of overriding
    if len(args['deviceClasses']) > 1:
        ignoreDefault = args['deviceClasses'].pop(0)
    for devClass in args['deviceClasses']:
        # ?Bug? (ZEN-31017) - work-around via multiple api calls
        # -- Get device classes first
        if args['exOrg']:
            print >> rOut, "#### {} extract of classes ####".format(devClass)
            apiResult = api.callMethod(
                'exportDevices',
                options={
                    'root': '/zport/dmd/Devices{}'.format(devClass),
Beispiel #27
0
if __name__ == '__main__':
    logging.basicConfig(
        format='%(asctime)s %(levelname)s %(name)s: %(message)s')
    logging.getLogger().setLevel(logging.ERROR)
    args = vars(buildArgs())
    log = logging.getLogger('zenApiLib')
    log.setLevel(args['loglevel'])
    if args['rFields']:
        rFields = args['rFields']
    else:
        rFields = ['result.success']
    rTotalResults = {}
    # Treat all API calls like paged calls
    zenapi = zenConnector(routerName=args['rName'],
                          cfgFilePath=args['configFilePath'],
                          section=args['configSection'],
                          loglevel=args['loglevel'])
    #cred file configuration override
    if args['timeout']:
        zenapi.config['timeout'] = args['timeout']
    for pagedResult in zenapi.pagingMethodCall(args['rMethod'],
                                               **args['data']):
        if not nested_get(pagedResult, ['result', 'success']) != "False":
            pprint(pagedResult)
            print " "
            log.error("API success FALSE")
            sys.exit(1)
        for rFieldName in rFields:
            if rFieldName.lower() == 'all':
                pprint(pagedResult)
            else:
Beispiel #28
0
import zenApiLib
import logging
from time import time, sleep

if not ('logging' in dir()):
    import logging
    logging.basicConfig(
        format = '%(asctime)s %(levelname)s %(name)s: %(message)s'
    )
    logging.getLogger().setLevel(logging.ERROR)

api = zenApiLib.zenConnector(section = 'default', routerName = 'JobsRouter')

def checkJobStatus(jobid):
    result = api.callMethod('getInfo', jobid=jobid)
    try:
        status = result['result']['data']['status']
    except (KeyError, ValueError):
        status = 'UNKNOWN! Invalid Job ID or other failure'
    return status

def watchStatus(jobid, timeout=300):
    '''
    This is a blocking method that will check on the status of
    a job every n seconds until it's either completed, aborted,
    failed, or a timeout is reached. It returns a tuple with the
    success status of the job, and a bool for Success or Failure
    '''
    jobStatus = 'Unknown'
    starttime = time()
    while jobStatus != 'SUCCESS':