def main(zabbix, user, password, host):
    zapi = ZabbixAPI(url=zabbix,
                     user=user, password=password)

    host_id = zapi.get_id(item_type='host', item=host)
    if host_id is None:
        create_zabbix_host(zapi=zapi, host=host)
    else:
        update_zabbix_host(zapi=zapi, host=host, host_id=host_id)
Esempio n. 2
0
def main(zabbix, user, password, host):
    zapi = ZabbixAPI(url=zabbix, user=user, password=password)

    host_id = zapi.get_id(item_type='host', item=host)
    if host_id is None:
        create_zabbix_host(zapi=zapi, host=host)
    else:
        update_zabbix_host(zapi=zapi, host=host, host_id=host_id)
# Read CSV file
hostFile = open(fileName)
hostReader = csv.reader(hostFile, delimiter=';', quotechar='|')
# Uncomment if your csv has headers
#headers = hostReader.next()
hostData = list(hostReader)

# CSV Parsing
for host in hostData:
    wantedGroups = []
    actualGroupIds = []
    hostName = host[1].split("-")[0]
    moveHost = False

    # Get Zabbixhost informations
    hostId = zapi.get_id('host', item=hostName, with_id=False, hostid=None)
    hostObj = zapi.host.get(hostids=hostId, selectGroups='extend')

    if hostId:
        # Create a comparison array of hostgroups id
        for hg in hostObj[0]['groups']:
            actualGroupIds.append(hg['groupid'])

        print "Working on ", hostName, " [id ", hostId, "]"

        for hostgroupName in host[0].split("-"):
            hostGroupId = zapi.get_id('hostgroup',
                                      item=hostgroupName,
                                      with_id=False,
                                      hostid=None)
            wantedGroups.append({'groupid': hostGroupId})
Esempio n. 4
0
class ZabbixCLI(ZabbixCLIArguments):

    def __init__(self, template=None):
        ZabbixCLIArguments.__init__(self)
        self._configureLogging()
        log.debug('Parser arguments: %s', self.args)

        # if no arguments, jsut print help
        if len(sys.argv) <= 1:
            self.argparser.print_help()
            sys.exit()

        if not self.args.get('template'):
            sys.exit('Template should be specified.')

        self.url = self.args['server']
        try:
            self.zapi = ZabbixAPI(
                self.url,
                user=self.args['user'],
                password=self.args['pass'])
        except:
            log.error('Error while trying open connection to zabbix server: %s',
                    self.url)

        # If we need to delete an object and exit
        if self.args.get('delete'):
            template_id = self.zapi.get_id('template', self.args['delete'][1])
            if ZabbixObject(self.zapi,
                            {'name': self.args['delete'][2]},
                            template_id=template_id,
                            obj_type=self.args['delete'][0]).delete():
                log.info(
                    '"{2}" {0} was deleted from "{1}"'.format(
                        *self.args['delete']))
            else:
                log.exit(
                    'Error while trying to delete: "{2}" {0} from "{1}"'.format(
                        *self.args['delete']))
            exit()

        # Set template name from __init__ params or args
        if template:
            self.template_name = template
        else:
            self.template_name = self.args.get('template')

        # Load template from file
        self.template = ZabbixTemplateFile(self.template_name, templates_dir=self.args.get('templates_dir'))
        self.template_id = None

        # When template loaded, set defaults and run apply process
        if self.template:
            self.config = ZabbixDefaults()
            self.apply()

    def _configureLogging(self):
        """
        Configure logging output. Format and colors.
        """

        # Set logging level
        if self.args.get('debug'):
            logLevel = logging.DEBUG
        else:
            logLevel = logging.INFO

        # Set colored output
        colors = {'reset': '\033[0m', 'green': '\x1b[32m', 'cyan': '\x1b[36m'}
        logFormat = '{reset}{cyan}[{green}%(asctime)s{cyan}]{reset} %(message)s'.format(
            **colors)
        logging.basicConfig(
            level=logLevel,
            format=logFormat,
            datefmt='%d/%m/%Y %H:%M:%S')

    def _apply_linked_templates(self):
        """
        Recursive apply list of linked templates. They will applied before main
        template will start applying.
        """

        if self.template.get('templates') and not self.args.get('only', False):
            log.info('%s depends from:', self.template.get('name'))
            # Show linked template list before applying
            for linked_template in self.template.get('templates', []):
                log.info("\t\t%s", linked_template)
            # Apply list of linked templates
            for linked_template in self.template.get('templates', []):
                ZabbixCLI(template=linked_template)

    def _apply_template(self, template):
        return ZabbixTemplate(self.zapi, template).apply()

    def _apply_macro(self, macro):
        ZabbixMacro(self.zapi, macro, self.template_id).apply()

    def _apply_macros(self):
        for macro in self.template.get('macros', []):
            self._apply_macro(macro)

    def _apply_app(self, app):
        return ZabbixApp(self.zapi, app, self.template_id).apply()

    def _apply_item(self, item):
        ZabbixItem(self.zapi, item, self.config, self.template_id).apply()

    def _apply_items(self, items, app_id):
        for item in items:
            item['app_id'] = app_id
            self._apply_item(item)

    def _apply_item_prototype(self, prototype):
        ZabbixItemPrototype(self.zapi, prototype, self.config, self.template_id).apply()

    def _apply_item_prototypes(self, discovery, app_id):
        items = discovery.get('items', [])
        rule_id = self.zapi.get_id(
            'discoveryrule',
            discovery['name'],
            templateid=self.template_id)
        for item in items:
            item.update({'rule_id': rule_id, 'app_id': app_id})
            self._apply_item_prototype(item)

    def _apply_graph(self, graph):
        ZabbixGraph(self.zapi, graph, self.config, self.template_id).apply()

    def _apply_graphs(self):
        for graph in self.template.get('graphs', []):
            self._apply_graph(graph)

    def _apply_graph_prototype(self, prototype):
        ZabbixGraphPrototype(self.zapi, prototype, self.config, self.template_id).apply()

    def _apply_graph_prototypes(self, discovery):
        graphs = discovery.get('graphs', [])
        for graph in graphs:
            self._apply_graph_prototype(graph)

    def _apply_trigger(self, trigger):
        ZabbixTrigger(self.zapi, trigger, self.config, self.template_id).apply()

    def _apply_triggers(self):
        for trigger in self.template.get('triggers', []):
            self._apply_trigger(trigger)

    def _apply_trigger_prototype(self, prototype):
        ZabbixTriggerPrototype(self.zapi, prototype, self.config, self.template_id).apply()

    def _apply_trigger_prototypes(self, discovery):
        triggers = discovery.get('triggers', [])
        for triggers in triggers:
            self._apply_trigger_prototype(triggers)

    def _apply_autoreg(self):
        autoreg = self.template.get('autoreg')
        if autoreg:
            ZabbixAutoreg(self.zapi, self.template).apply()

    def _apply_trigger_action(self):
        alerts = self.template.get('alerts', [])
        for alert in alerts:
            ZabbixTriggerAction(self.zapi, alert, self.config, self.template_id, self.template_name).apply()

    def _apply_discovery(self, discovery):
        ZabbixDiscovery(self.zapi, discovery, self.config, self.template_id).apply()

    def _apply_discoveries(self):
        discoveries = self.template.get('discovery', {})

        for app, discovery in discoveries.iteritems():
            app_id = self._apply_app(app)
            self._apply_discovery(discovery)
            self._apply_item_prototypes(discovery, app_id)
            self._apply_graph_prototypes(discovery)
            self._apply_trigger_prototypes(discovery)

    def _disable_item(self, id_):
        ZabbixItem(self.zapi).disable(id_)

    def _disable_app(self, app):
        items = self.zapi.get_id(
            'item',
            None,
            hostid=self.template_id,
            app_name=app)
        for item in items:
            self._disable_item(item)

    def clean(self):
        """
        Find and clean unused zabbix objects in current template.
        """

        def getUnusedObjects(type_, o):
            """
            Return list of unused zabbix objects of specific type in current template
            """

            unused_items = []
            # Get current objects from current template
            current_items = self.zapi.get_id(type_, templateids=self.template_id, name=True)
            if current_items:
                log.debug("Current %s: %s", type_, current_items)
                template_items = []
                for item in o:
                    if isinstance(item, dict):
                        template_items.append(item.get('name'))
                    else:
                        template_items.append(item)
                log.debug("Template %s: %s", type_, template_items)
                # Filter out similar objects from zabbix and template
                unused_items = filter(lambda x: x not in template_items, current_items)
                log.debug("Unused %s: %s", type_, unused_items)
            return { type_: unused_items }

        def removeObjects(template_objects):
            """
            Remove unused zabbix objects in current template.
            """

            # Find unused objects
            for objects in template_objects:
                unused_objects = getUnusedObjects(*objects)
                # Process each object type
                for type_, objects_list in unused_objects.iteritems():
                    # Get zabbix id for each unused object
                    for name in objects_list:
                        object_id = self.zapi.get_id(type_, name)
                        if object_id:
                            # Make function to remove object
                            func = 'self.zapi.{object_type}.delete'.format(object_type=type_)
                            log.info('Unused: %s \'%s\' was removed', type_, name)
                            eval(func)(object_id)

        # Init lists for objects
        items = apps = discovery = itemprototype = graphprototype = triggerprototype = []

        for app, item in self.template.get('applications', {}).iteritems():
            apps.append(app)
            items.extend(item)
        for app, disc in self.template.get('discovery', {}).iteritems():
            apps.append(app)
            discovery.append(disc)
            itemprototype.extend(disc.get('items', {}))
            graphprototype.extend(disc.get('graphs',{}))
            triggerprototype.extend(disc.get('triggers', {}))

        # Cleanup should be executed in folowing order
        obj_for_cleanup = collections.OrderedDict()
        obj_for_cleanup['application'] = apps
        obj_for_cleanup['item'] = items
        obj_for_cleanup['usermacro'] = map(lambda x: {'name':x.get('macro')}, self.template.get('macros', []))
        obj_for_cleanup['graph'] = self.template.get('graphs', [])
        obj_for_cleanup['trigger'] = self.template.get('triggers', [])
        obj_for_cleanup['discoveryrule'] = discovery
        obj_for_cleanup['itemprototype'] = itemprototype
        obj_for_cleanup['graphprototype'] = graphprototype
        obj_for_cleanup['triggerprototype'] = triggerprototype

        # Make tuple (obj_type, value) to compare with
        template_objects = []
        for k,v in obj_for_cleanup.iteritems():
            template_objects.append((k,v))

        # Remove unused objects
        removeObjects(template_objects)

    def apply(self):
        """
        Apply current template to zabbix.
        """

        self._apply_linked_templates()
        self.template_id = self._apply_template(self.template)

        # Cleanup unused objects
        self.clean()

        apps = self.template.get('applications', {})
        for app, items in apps.iteritems():
            # check if disabled whole app
            if str(items).lower() == 'disabled':
                self._disable_app(app)
            else:
                app_id = self._apply_app(app)
                self._apply_items(items, app_id)

        self._apply_macros()
        self._apply_graphs()
        self._apply_triggers()
        self._apply_discoveries()
        self._apply_autoreg()
        self._apply_trigger_action()
        log.info("Done: '%s'", self.template.get('name'))
# all other stdin lines contains a trap itself
trapstr = inp.read().rstrip()

logging.debug("hostname is: %s", hostname)
logging.debug("IP address is: %s", ip)
logging.debug("trap info is: %s", trapstr)

logging.debug("api_config: %s, %s, %si", api_config['zabbix_url'],
              api_config['zabbix_user'], api_config['zabbix_passwd'])

# using ZabbixAPI check if a hostname and a corresponding item exists
z = ZabbixAPI(api_config['zabbix_url'],
              user=api_config['zabbix_user'],
              password=api_config['zabbix_passwd'])

hostid = z.get_id("host", item=hostname)
if not hostid:
    # device's hostname may not match to the one in zabbix
    # in this case try to find out a hostname by the device's ipaddress
    res = z.hostinterface.get(search={'ip': ip},
                              output=['hostid', 'interfaceid'])
    if not res:
        logging.error("there is no hostname %s in Zabbix. Discarding trap...",
                      hostname)
        exit(1)

    hostid = res[0]['hostid']

    res = z.host.get(hostids=hostid, output=['hostid', 'name'])
    if not res:
        logging.error("there is no hostname %s in Zabbix. Discarding trap...",
Esempio n. 6
0
def main():
    parser = ArgumentParser()
    parser.add_argument("-z", "--zabbix", help="Zabbox URL", required=True)
    parser.add_argument("-u", "--user", help="Zabbix user name", required=True)
    parser.add_argument("-p",
                        "--password",
                        help="Zabbix user password",
                        required=True)
    parser.add_argument("-D",
                        "--dir",
                        help="Directory where charts will be saved",
                        required=True)
    parser.add_argument("-s",
                        "--start_time",
                        help="Chart data start time",
                        required=True)
    parser.add_argument("-d",
                        "--duration",
                        help="Chart data duration",
                        required=True)
    parser.add_argument("-H", "--host", help="Host name", required=True)
    args = parser.parse_args()
    zabbix = args.zabbix
    user = args.user
    password = args.password
    host = args.host
    start_time = args.start_time
    duration = int(args.duration)
    chart_dir = args.dir

    if duration < 60:
        duration = 60

    zapi = ZabbixAPI(url=zabbix, user=user, password=password)

    host_id = zapi.get_id(item_type='host', item=host)

    zapi = ZabbixAPI(url=zabbix, user=user, password=password)
    graphs = zapi.do_request(method="graph.get", params={"hostids":
                                                         host_id})['result']

    graph_ids = {}
    for graph in graphs:
        if graph['name'] in GRAPH_NAMES:
            graph_ids[graph['graphid']] = graph['name']

    s = requests.Session()
    payload = {
        'name': user,
        'password': password,
        'enter': 'Sign in',
        'autologin': '******',
        'request': ''
    }
    url = "{0}/index.php?login=1".format(zabbix)
    s.post(url, data=payload)
    for graph_id, graph_name in graph_ids.iteritems():
        url = ("{0}/chart2.php?"
               "graphid={1}&stime={2}&period={3}".format(
                   zabbix, graph_id, start_time, duration))
        response = s.get(url, stream=True)
        file_name = "{0}/{1}-{2}.png".format(chart_dir, host,
                                             graph_name.replace(" ", "_"))
        with open(file_name, 'wb') as f:
            shutil.copyfileobj(response.raw, f)
Esempio n. 7
0
#!/usr/bin/env python

import sys
from zabbix.api import ZabbixAPI

if len(sys.argv) > 1:
    hostname = sys.argv[1]

z = ZabbixAPI(
        url='https://zabbix.local',
        user='******',
        password='******')

# Get zabbix host id
hostId = z.get_id('host', hostname)

# Remove host by id
result = z.do_request('host.delete', [hostId]).get('result', {}).get('hostids',[None])[0]

# Output
if result:
    print '{hostname} removed from zabbix.'.format(hostname=hostname)
else:
    sys.exit(1)
Esempio n. 8
0
def main(argv):
    print('-- Host Bulk Insert --')

    # Parse arguments and build work variables
    args = ArgumentParser()
    zabbixURL = args.Z
    zabbixUsername = args.u
    zabbixPassword = args.p
    csvFile = args.f

    hostGroupNames = []
    templateNames = []
    proxyNames = []

    hostGroupId = {}
    templateId = {}
    proxyId = {}

    # Static values from zabbix api
    interfaceType = {'agent': 1, 'SNMP': 2, 'IMPI': 3, 'JMX': 4}

    print('Reading CSV file: {}'.format(csvFile))
    hostData = parseCSV(csvFile, ';')
    # jsonPrint(hostData)

    # API Connect
    print('Connecting to {}'.format(zabbixURL))
    zapi = ZabbixAPI(url=zabbixURL,
                     user=zabbixUsername,
                     password=zabbixPassword)

    print('Parsing templates, proxy and hostgroups')

    # Read all host groups and templates
    for host in hostData:
        for hostgroupName in host['Groups'].split(","):
            hostGroupNames.append(hostgroupName)

        for templateName in host['Templates'].split(","):
            if templateName != 'DO_NOT_ADD':
                templateNames.append(templateName)

        if len(host['Proxy']) > 0:
            proxyNames.append(host['Proxy'])

    print('Templates: {}'.format(set(templateNames)))
    print('Hostgroups: {}'.format(set(hostGroupNames)))
    print('Proxyes: {}'.format(set(proxyNames)))

    # Foreach UNIQUE hostgroup, create if missing
    for hostgroupName in set(hostGroupNames):
        if (zapi.get_id('hostgroup',
                        item=hostgroupName,
                        with_id=False,
                        hostid=None) == None):
            print('Creating missing hostgroup: {}'.format(hostgroupName))
            zapi.hostgroup.create(name=hostgroupName)
        # Create associative array Name=>Id
        hostGroupId[hostgroupName] = zapi.get_id('hostgroup',
                                                 item=hostgroupName,
                                                 with_id=False,
                                                 hostid=None)

    # Foreach UNIQUE template
    for templateName in set(templateNames):
        # TODO : what if template does not exist ?
        # Create associative array Name=>Id
        templateId[templateName] = zapi.get_id('template',
                                               item=templateName,
                                               with_id=False,
                                               hostid=None)

    # Foreach UNIQUE proxy
    for proxyName in set(proxyNames):
        # TODO : what if proxy does not exist ?
        # Create associative array Name=>Id

        f = {'host': proxyName}
        proxyObj = zapi.proxy.get(filter=f)
        proxyId[proxyName] = proxyObj[0]['proxyid']

    # Create objects and add hosts
    for host in hostData:
        h_groups = []
        h_templates = []
        h_name = host['Hostname']
        h_desc = host['Description']
        h_ip = host['IP Address']
        h_dns = host['DNSName']

        h_interfaces = []
        h_proxy = host['Proxy']
        h_tags = []
        h_macros = []

        if (host['Interfaces'] == 'DO_NOT_ADD'):
            print('Skipping host: {}'.format(h_name))
            continue

        if len(host['DNSName']) > 0:
            h_useip = 0
        else:
            h_useip = 1

        # Check and skip existing hosts
        if args.s:
            f = {'host': h_name}
            hosts = zapi.host.get(filter=f,
                                  output='extend',
                                  selectTags='extend')
            if hosts:
                print('Host {} already exists!! Skpping'.format(h_name))
                continue

        print('Working on: {}'.format(h_name))

        # Build Tags object
        if len(host['Tags']) > 0:
            for tagString in host['Tags'].split(","):
                [tagName, tagValue] = tagString.split("=")
                h_tags.append({'tag': tagName, 'value': tagValue})
            # jsonPrint(h_tags)

        # Build Macro object
        if len(host['Macros']) > 0:
            for macroString in host['Macros'].split(","):
                [macroName, macroValue] = macroString.split("=")
                h_macros.append({'macro': macroName, 'value': macroValue})
            # jsonPrint(h_macros)

        # Build interface object
        for interface in host['Interfaces'].split(","):
            if (interfaceType[interface] == 1):
                port = 10050
            else:
                port = 161

            h_interfaces.append({
                'type': interfaceType[interface],
                'main': 1,
                'useip': h_useip,
                'ip': h_ip,
                'dns': h_dns,
                'port': port
            })

        # Build hostgroup object
        for hostgroup in host['Groups'].split(","):
            h_groups.append({
                'groupid': hostGroupId[hostgroup],
            })

        # Build template object
        for template in host['Templates'].split(","):
            h_templates.append({
                'templateid': templateId[template],
            })

        if len(h_proxy) > 0:
            zapi_result = zapi.host.create(host=h_name,
                                           tags=h_tags,
                                           description=h_desc,
                                           interfaces=h_interfaces,
                                           groups=h_groups,
                                           templates=h_templates,
                                           proxy_hostid=proxyId[h_proxy],
                                           macros=h_macros)

        else:

            zapi_result = zapi.host.create(host=h_name,
                                           tags=h_tags,
                                           description=h_desc,
                                           interfaces=h_interfaces,
                                           groups=h_groups,
                                           templates=h_templates,
                                           macros=h_macros)
        jsonPrint(zapi_result)
def main():
    parser = ArgumentParser()
    parser.add_argument("-z", "--zabbix",
                        help="Zabbox URL",
                        required=True)
    parser.add_argument("-u", "--user",
                        help="Zabbix user name",
                        required=True)
    parser.add_argument("-p", "--password",
                        help="Zabbix user password",
                        required=True)
    parser.add_argument("-D", "--dir",
                        help="Directory where charts will be saved",
                        required=True)
    parser.add_argument("-s", "--start_time",
                        help="Chart data start time",
                        required=True)
    parser.add_argument("-d", "--duration",
                        help="Chart data duration",
                        required=True)
    parser.add_argument("-H", "--host",
                        help="Host name",
                        required=True)
    args = parser.parse_args()
    zabbix = args.zabbix
    user = args.user
    password = args.password
    host = args.host
    start_time = args.start_time
    duration = int(args.duration)
    chart_dir = args.dir

    if duration < 60:
        duration = 60

    zapi = ZabbixAPI(url=zabbix,
                     user=user, password=password)

    host_id = zapi.get_id(item_type='host', item=host)

    zapi = ZabbixAPI(url=zabbix,
                     user=user, password=password)
    graphs = zapi.do_request(method="graph.get",
                             params={"hostids": host_id})['result']

    graph_ids = {}
    for graph in graphs:
        if graph['name'] in GRAPH_NAMES:
            graph_ids[graph['graphid']] = graph['name']

    s = requests.Session()
    payload = {'name': user,
               'password': password,
               'enter': 'Sign in',
               'autologin': '******',
               'request': ''}
    url = "{0}/index.php?login=1".format(zabbix)
    s.post(url, data=payload)
    for graph_id, graph_name in graph_ids.iteritems():
        url = ("{0}/chart2.php?"
               "graphid={1}&stime={2}&period={3}".format(zabbix,
                                                         graph_id,
                                                         start_time,
                                                         duration))
        response = s.get(url, stream=True)
        file_name = "{0}/{1}-{2}.png".format(chart_dir,
                                             host,
                                             graph_name.replace(" ", "_"))
        with open(file_name, 'wb') as f:
            shutil.copyfileobj(response.raw, f)