class ZabbixTemplates:
    def __init__(self, _url, _user, _password):
        self.zapi = ZabbixAPI(url=_url, user=_user, password=_password)

    def exportTemplates(self, args):
        request_args = {"output": "extend"}

        if args.templates != 'All':
            request_args.filter = {"host": [args.tempaltes]}

        result = self.zapi.do_request('template.get', request_args)
        if not result['result']:
            print "No matching host found for '{}'".format(hostname)
            exit(-3)

        if result['result']:
            for t in result['result']:
                dest = args.out_dir + '/' + t['host'] + '.xml'
                self.exportTemplate(t['templateid'], dest)

    def exportTemplate(self, tid, oput):

        print "tempalteid:", tid, " output:", oput
        args = {"options": {"templates": [tid]}, "format": "xml"}

        result = self.zapi.do_request('configuration.export', args)
        template = xml.dom.minidom.parseString(
            result['result'].encode('utf-8'))
        date = template.getElementsByTagName("date")[0]
        # We are backing these up to git, steralize date so it doesn't appear to change
        # each time we export the templates
        date.firstChild.replaceWholeText('2016-01-01T01:01:01Z')
        f = open(oput, 'w+')
        f.write(template.toprettyxml().encode('utf-8'))
        f.close()
Esempio n. 2
0
class ZabbixTemplates:
    def __init__(self, _url, _user, _password):
        self.zapi = ZabbixAPI(url=_url, user=_user, password=_password)

    def exportTemplates(self, args):
        request_args = {"output": "extend"}

        if args.templates != 'All':
            request_args.filter = {"host": [args.tempaltes]}

        result = self.zapi.do_request('template.get', request_args)
        if not result['result']:
            print "No matching host found for '{}'".format(hostname)
            exit(-3)

        if result['result']:
            for t in result['result']:
                dest = args.out_dir + '/' + t['host'] + '.json'
                self.exportTemplate(t['templateid'], dest)

    def exportTemplate(self, tid, oput):

        print "tempalteid:", tid, " output:", oput
        args = {"options": {"templates": [tid]}, "format": "json"}

        result = self.zapi.do_request('configuration.export', args)
        jsondump = json.dumps(result['result'])
        template = json.loads(jsondump)

        f = open(oput, 'w+')
        f.write(template)
        f.close()
Esempio n. 3
0
def list_hosts():
    zbx_host = sys.argv[1]
    zbx_user = sys.argv[2]
    zbx_pass = sys.argv[3]
    zbx_filter = sys.argv[4]
    zbx_filter_value = sys.argv[5]
    zbx_psk_identity = sys.argv[6]
    zbx_psk = sys.argv[7]

    zapi = ZabbixAPI(url=zbx_host, user=zbx_user, password=zbx_pass)
    if zbx_filter == 'host':
        res1 = zapi.do_request('host.get', {
            'search': {
                'host': zbx_filter_value
            },
            'output': ['hostid', 'name']
        })
        hosts = res1.get(u'result')
    if zbx_filter == 'template':
        res1 = zapi.do_request(
            'template.get', {
                'filter': {
                    'host': zbx_filter_value
                },
                'selectHosts': 'extend',
                'output': ['hostid', 'name']
            })
        hosts = res1.get(u'result')[0].get(u'hosts')
    if zbx_filter == 'proxy':
        res1 = zapi.do_request(
            'proxy.get', {
                'filter': {
                    'host': zbx_filter_value
                },
                'selectHosts': 'extend',
                'output': ['hostid', 'name']
            })
        hosts = res1.get(u'result')[0].get(u'hosts')
    if zbx_filter == 'host' or zbx_filter == 'template' or zbx_filter == 'proxy':
        print('Following hosts will be updated:')
        for host in hosts:
            print(host.get(u'name'))
        zapi.do_request(
            'host.massupdate', {
                'hosts': hosts,
                'tls_connect': 2,
                'tls_accept': 2,
                'tls_psk_identity': zbx_psk_identity,
                'tls_psk': zbx_psk
            })
Esempio n. 4
0
def zbx_call(method, args):
    zapi = ZabbixAPI(url=settings.ZABBIX_URL, user=settings.ZABBIX_USER, password=settings.ZABBIX_PASSWD)
    args = args.replace("'", '"')
    args = json.loads(args)
    if method == "service.get" and args.get("serviceids"):
        key = ""
        for srv_id in args["serviceids"]:
            key += srv_id
        cached = cache.get(key)
        if cached:
            return cached
        else:
            result = zapi.do_request(method, args)
            cache.set(key, result, None)
            return result
    result = zapi.do_request(method, args)
    return result
Esempio n. 5
0
def zbx_call(method, args):
    zapi = ZabbixAPI(url=settings.ZABBIX_URL,
                     user=settings.ZABBIX_USER,
                     password=settings.ZABBIX_PASSWD)
    args = args.replace("'", "\"")
    args = json.loads(args)
    if method == "service.get" and args.get('serviceids'):
        key = ""
        for srv_id in args['serviceids']:
            key += srv_id
        cached = cache.get(key)
        if cached:
            return cached
        else:
            result = zapi.do_request(method, args)
            cache.set(key, result, None)
            return result
    result = zapi.do_request(method, args)
    return result
Esempio n. 6
0
class zabbix_data:
    __zapi = ''

    def __init__(self):
        conf = app_config()
        config_value = conf.get_config_value()
        self.__zapi = ZabbixAPI(url=config_value['zabbix_api_addr'][0],
                                user=config_value['zabbix_api_user'][0],
                                password=config_value['zabbix_api_user'][1])

    def host_trigger_get(self, params):
        warn = []
        disable = []
        enable = []
        result = self.__zapi.do_request('host.get', params)['result']
        for i in range(len(result)):
            result[i]['triggers'] = list(
                filter(lambda x: x['value'] == "1" and x['status'] == "0",
                       result[i]['triggers']))
            if result[i]['status'] == '1':
                disable.append(result[i])
            elif result[i]['triggers']:
                warn.append(result[i])
            else:
                enable.append(result[i])
        return warn + enable + disable

    def item_history_get(self, params):
        result = self.__zapi.do_request("history.get", params)["result"]
        return result

    def host_item_get(self, params):
        result = self.__zapi.do_request("host.get", params)["result"]
        return result

    def item_get(self, params):
        result = self.__zapi.do_request("item.get", params)["result"]
        return result
Esempio n. 7
0
def check_stat(hostlist):
    print hostlist
    zapi = ZabbixAPI(url=environ['ZABBIX_URL'],
                     user=environ['ZABBIX_USER'],
                     password=environ['ZABBIX_PASSWORD'])
    status = "green"
    for host in hostlist:
        result = zapi.do_request('trigger.get', {
            'active': 1,
            'only_true': 1,
            'hostids': host
        })['result']
        for x in xrange(len(result)):
            if int(result[x]['priority']) > 3:
                status = "red"
    return status
Esempio n. 8
0
def main(argv):

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

    zapi = ZabbixAPI(url=zabbixURL,
                     user=zabbixUsername,
                     password=zabbixPassword)

    params = []
    for triggerid in args.i.split(' '):
        trigObj = {"triggerid": triggerid, "status": args.s}
        params.append(trigObj)

    # Call request directly for the custom param field, instead of using zapi.trigger.update
    result = zapi.do_request('trigger.update', params=params)
    jsonPrint(result)
Esempio n. 9
0
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.plugins.callback import CallbackBase
import ansible.constants as C

#zabbix服务器自动添加删除维护,并且自动添加执行ansible-playbook自动安装客户端
pool = redis.ConnectionPool(host="54.223.98.251", port=6379, db=10)
redis_cli = redis.Redis(connection_pool=pool)
zapi = ZabbixAPI(url='http://zabbix.guokr.com',
                 user='******',
                 password='******')
Ec2_keys = ["InstanceId", "PrivateIpAddress", "State", "Tags"]
already_maintenance = zapi.do_request("maintenance.get")["result"]
ansible_hosts_file = "/data/ansible/test_playbook_api_host"
playbook_yaml_path = '/data/ansible/test.yml'


class ansible_playbook(object):
    def __init__(self, ansible_hostsfile):
        self.ansible_hostsfile = ansible_hostsfile
        self.loader = DataLoader()
        self.inventory = InventoryManager(loader=self.loader,
                                          sources=self.ansible_hostsfile)
        self.variable_manager = VariableManager(loader=self.loader,
                                                inventory=self.inventory)
        self.Options = namedtuple('Options', [
            'connection', 'remote_user', 'ask_sudo_pass', 'verbosity',
            'ack_pass', 'module_path', 'forks', 'become', 'become_method',
Esempio n. 10
0
import re

templateid = "10242" # enter your own template id here!

# Create ZabbixAPI class instance
user = '' # enter your own here!
password = '' # enter your own here!
zapi = ZabbixAPI(url='https://xtee-monitor.ci.kit/', user=user, password=password)

# Get all monitored hosts
result1 = zapi.host.get(monitored_hosts=1, output='extend')

# Get all disabled hosts
result2 = zapi.do_request('host.get',
                          {
                              'filter': {'status': 1},
                              'output': 'extend'
                          })

# Filter results
hostnames1 = [host['host'] for host in result1]
hostnames2 = [host['host'] for host in result2['result']]

# Example stdin:
# XTEE-CI/GOV/00000000/00000000_1/xtee4.ci.kit
# XTEE-CI/GOV/00000001/00000001_1/xtee5.ci.kit
# XTEE-CI/COM/00000002/00000002_1/xtee6.ci.kit
# Server name part is "greedy" match to allow server names to have "/" character
for line in sys.stdin:
    m = re.match("^(.+?)/(.+?)/(.+?)/(.+)/(.+?)$", line)
Esempio n. 11
0
                         user=zabbix_user,
                         password=zabbix_password)
    except Exception, e:
        print e, 'ZabbixAPI: Authenticate failed.'

    # Get Zabbix API version
    try:
        result_version = zapi.api_version()
    except:
        result_version = "2.4"

    # Hostgroup get
    hostgroup = system_name
    try:
        result_hostgroup = zapi.do_request('hostgroup.get',
                                           {'filter': {
                                               'name': hostgroup
                                           }})
        if not result_hostgroup['result']:
            print 'Can not be found host group ' + hostgroup
            exit(-1)
        else:
            hostgroup_id = result_hostgroup['result'][0]['groupid']
    except Exception, e:
        print e, 'ZabbixAPI: hostgroup.get exist failed.'

    # Host get
    hostname = system_domain
    try:
        result_host = zapi.do_request('host.get',
                                      {'filter': {
                                          'name': hostname
import argparse
import sys

from zabbix.api import ZabbixAPI
from get_zabbix_secrets import get_secret

ZABBIX_USER, ZABBIX_PASSWORD = get_secret()

ZABBIX_SERVER = "http://zabbix-web-nginx-pgsql-clusterip"

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Delete host from Zabbix server")
    parser.add_argument("-n", "--hostname", required=True, help="Zabbix hostname")
    args = parser.parse_args()

    zapi = ZabbixAPI(url=ZABBIX_SERVER, user=ZABBIX_USER, password=ZABBIX_PASSWORD)

    """Get hostid by hostname"""
    result = zapi.do_request(
        "host.get", {"filter": {"host": [args.hostname]}, "output": ["name", "hostid"]}
    )

    if not result["result"]:
        sys.exit("hostname not found")

    """Delete host from Zabbix server"""
    hostid = result["result"][0]["hostid"]
    result = zapi.do_request("host.delete", [hostid])
    print(result)
Esempio n. 13
0
# simple parse for arguments
url = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
zhost = sys.argv[4]
name = sys.argv[5]
print "Going to connect to {} as {}".format(url, user)
print("Will try to update zabbix host {} with a visible name of {}".format(
    zhost, name))

# Create ZabbixAPI class instance
use_older_authenticate_method = False
zapi = ZabbixAPI(url, use_older_authenticate_method, user, password)

zversion = zapi.do_request('apiinfo.version')
print "Zabbix API version: {}".format(zversion['result'])

# Get host
print "----------------------------"
enabledhosts = zapi.do_request('host.get', {'filter': {'host': zhost}})
print enabledhosts
print("==========")
hostnames = [host['host'] for host in enabledhosts['result']]
print "Found hosts: {}".format(hostnames)

# only want single host operations
if len(hostnames) > 1:
    print("This name update is only meant for single hosts.")
    exit(1)
elif len(hostnames) == 0:
Esempio n. 14
0
#         itm = get_item('{0} - java threads'.format(self.app_short_name), self.template, self.application)
#         itm.key = 'jmx[java.lang:type=Threading, ThreadCount]'
#         itm.type = zabbixmgm.zbxitem.TYPE_JMX_AGENT
#         commit_item(itm)
#         self.items.append(itm)

#     def assign_to_host(self, host, port):
#         host.add_template(self.template)
#         intf = get_interface(host, port, itype=zabbixmgm.zbxinterface.TYPE_JMX)
#         # intf.type =
#         host.add_interface(intf)
#         commit_host(host)

# ec = eventCorrelator()
# ag = applicationservice()

pdb.set_trace()
grp = create_group("MCng Backend")
oslinuxtmplate = get_template('Template OS Linux', grp)
pdb.set_trace()

for i in [3, 4, 5, 6, 7, 8]:
    n3 = get_host('52n0{0}.s52.local'.format(i), create_group("MCng Backend"))
    n3.add_template(oslinuxtmplate)
    c, l = n3.get()

    zapi.do_request(c, l)

# ec.assign_to_host(n3, '40002')
# ag.assign_to_host(n3, '40003')
Esempio n. 15
0
    except KeyError, e:
        module.fail_json(msg='Missing actions data: %s is not set.' % e.message)

    try:
        login = module.params['login']
        password = module.params['password']
        server = module.params['server']
    except KeyError, e:
        module.fail_json(msg='Missing login data: %s is not set.' % e.message)

    try:
        zabbix_object = module.params['object']
        params = module.params['params']
    except KeyError, e:
        module.fail_json(msg='Missing actions data: %s is not set.' % e.message)

    try:
        zapi = ZabbixAPI(url=server, user=login, password=password)
    except BaseException as e:
        module.fail_json(msg='Authentication error: %s' % e)

    try:
        request = zapi.do_request(zabbix_object + '.' + action, params)
    except BaseException as e:
        module.fail_json(msg='Request error: %s ' % e)

    module.exit_json(changed=1, ansible_facts={'response': request})

main()

Esempio n. 16
0
                    datefmt='%m/%d/%Y %I:%M:%S %p')
logger = logging.getLogger(__name__)

# Create ZabbixAPI class instance
zapi = ZabbixAPI(url='http://192.168.0.249/zabbix/',
                 user='******',
                 password='******')

zhost = "WEBSCENARIO-ABDI"

# Get all disabled hosts
result2 = zapi.do_request(
    'host.get',
    {
        'filter': {
            'host': [zhost]
        },
        #'filter': {'status': 1},
        'output': 'extend'
    })

# Filter results
hostname = result2['result'][0][
    'host']  #[host['host'] for host in result2['result']]
hostid = result2['result'][0]['hostid']
print(hostname)
print(hostid)

zversion = zapi.do_request('apiinfo.version')
print("Zabbix API version: {}".format(zversion['result']))
version_number = zversion['result']
def get_classify_one_datapoint(trained_models):
    #getting the data
    #create varialbles to authenticate later
    url = "http://10.1.8.88/zabbix"
    user = "******"
    password = "******"
    host = "Server2"
    key = "vfs.fs.size[/,free]"
    use_older_authenticate_method = False

    # Create ZabbixAPI class instance
    zapi = ZabbixAPI(url, use_older_authenticate_method, user, password)
    thehost = zapi.do_request('host.get', {
        'filter': {
            'host': host
        },
        'selectItems': 'extend',
        'output': 'extend'
    })
    if len(thehost['result']) < 1:
        print(
            "HALTING. There was no host defined in zabbix with id: {}".format(
                host))
        sys.exit(2)
    hostId = thehost['result'][0]['hostid']

    #get metrics for that host
    history = zapi.do_request('item.get', {
        "output": "extend",
        "hostids": hostId,
        "sortfield": 'name'
    })
    print(len(history['result']))
    #following are the metrics that we need to pass to our algo
    items_we_need = [
        'system.cpu.load[percpu,avg1]', 'system.cpu.intr',
        'system.cpu.switches', 'system.cpu.util[,idle]',
        'system.cpu.util[,interrupt]', 'system.cpu.util[,iowait]',
        'system.cpu.util[,nice]', 'system.cpu.util[,softirq]',
        'system.cpu.util[,steal]', 'system.cpu.util[,system]',
        'system.cpu.util[,user]', 'proc.num[,,run]', 'net.if.in[ens32]',
        'net.if.in[virbr0-nic]', 'net.if.in[virbr0]', 'net.if.out[ens32]',
        'net.if.out[virbr0-nic]', 'net.if.out[virbr0]',
        'system.swap.size[,free]', 'vfs.fs.inode[/,pfree]',
        'vfs.fs.size[/,free]', 'vfs.fs.size[/,used]',
        'vm.memory.size[available]'
    ]
    #create a list of the metrics we need from the fetched list
    list1 = []
    for i in range(0, len(history['result'])):
        for item in items_we_need:
            if history['result'][i]['key_'] == item:
                list1.append(float(history['result'][i]['lastvalue']))
                print(history['result'][i]['lastvalue'],
                      history['result'][i]['key_'],
                      history['result'][i]['lastclock'])

    #return this value
    X_test = numpy.array(list1)

    #classifying the data:
    for model in trained_models:
        predicted_class = int(model.predict(X_test.reshape(1, -1)))
        print("predicted_class = ", predicted_class)
        #if predicted_class != 1:
        #t = threading.Thread(target = send_mail, args = (predicted_class, ))
        #t.start()
        print(" \n")
Esempio n. 18
0
                         e.message)

    try:
        login = module.params['login']
        password = module.params['password']
        server = module.params['server']
    except KeyError, e:
        module.fail_json(msg='Missing login data: %s is not set.' % e.message)

    try:
        zabbix_object = module.params['object']
        params = module.params['params']
    except KeyError, e:
        module.fail_json(msg='Missing actions data: %s is not set.' %
                         e.message)

    try:
        zapi = ZabbixAPI(url=server, user=login, password=password)
    except BaseException as e:
        module.fail_json(msg='Authentication error: %s' % e)

    try:
        request = zapi.do_request(zabbix_object + '.' + action, params)
    except BaseException as e:
        module.fail_json(msg='Request error: %s ' % e)

    module.exit_json(changed=1, ansible_facts={'response': request})


main()
class Zabbix(MonitorConnector):
    def __init__(self, url, user, password):
        try:
            self.server = ZabbixAPI(url=url, user=user, password=password)
        except Exception as error:
            STREAM.error("Cannot establish Zabbix session: {}".format(error))
            exit(1)

    def _get_host(self, hostname):
        host = self.server.do_request("host.get", {
            "output": "extend",
            "filter": {
                "host": hostname,
                "status": 0
            }
        })
        if host["result"]:
            return host
        else:
            STREAM.error("Cannot find specific host: {}".format(hostname))
            return None

    def _get_metric(self, host_id, metric):
        item = self.server.do_request("item.get", {
            "output": "extend",
            "hostids": host_id,
            "search": {
                "key_": metric
            },
        })
        if item["result"]:
            return item
        else:
            STREAM.error("Cannot find specific metric: {}".format(metric))
            return None

    def _get_metric_value(self, metric_id):
        value = self.server.do_request(
            "history.get", {
                "output": "extend",
                "history": 0,
                "itemids": metric_id,
                "sortfield": "clock",
                "sortorder": "DESC",
                "limit": 1
            })
        if value["result"]:
            return value
        else:
            STREAM.error("Cannot retrieve value for item: {}".format(value))
            return None

    def get_metric(self, hostname, metric):
        host = self._get_host(hostname)
        if host is None:
            return -1
        # Внутренний ID хоста в Zabbix.
        host_id = host["result"][0]["hostid"]
        # Состояние наблюдаемого хоста в Zabbix. (1 - наблюдается, 2 - не наблюдается).
        host_status = host["result"][0]["available"]

        if host_status == "1":
            metric = self._get_metric(host_id, metric)
            if metric is None:
                return -1
            else:
                metric_id = metric["result"][0]["itemid"]
                metric_value = self._get_metric_value(metric_id)
                if metric_value is None:
                    return -1
                else:
                    return json.loads(metric_value["result"][0]["value"])
        else:
            return -1
Esempio n. 20
0
from zabbix.api import ZabbixAPI
from flask import current_app as app
import re
from datetime import datetime

zapi = ZabbixAPI(url=app.config['ZABBIX_URL'],
                 user=app.config['ZABBIX_USER'],
                 password=app.config['ZABBIX_PASSWORD'])
zab_server = zapi.do_request(
    "host.get", {"search": {
        "name": "Zabbix server",
        "host": "Zabbix server"
    }})
zab_hostid = zab_server["result"][0]["hostid"]
zab_web_apps_name = ["mooc", "science"]


def zab_web_itemids(app_name):
    app_item_id = {
        "download_speed": "",
        "response_time": "",
        "response_code": ""
    }
    app_itemids = zapi.do_request(
        "item.get", {
            "hostids": zab_hostid,
            "webitems": "true",
            "search": {
                "key_": app_name,
            },
        })
Esempio n. 21
0
  print "USAGE: zabbixURL user pass"
  print "EXAMPLE: http://127.0.0.1/zabbix Admin zabbix"
  sys.exit(1)

# simple parse for arguments
url = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
print "Going to connect to {} as {}".format(url,user)


# Create ZabbixAPI class instance
use_older_authenticate_method = False
zapi = ZabbixAPI(url, use_older_authenticate_method, user, password)

zversion = zapi.do_request('apiinfo.version')
print "Zabbix API version: {}".format(zversion['result'])

# https://www.zabbix.com/documentation/2.2/manual/api/reference/host/get
# Get all enabled hosts
print "----------------------------"
enabledhosts = zapi.do_request('host.get',
                          {
                              'filter': {'status': '0'},
                              'output': 'extend'
                          })
hostnames = [host['host'] for host in enabledhosts['result']]
print "All enabled hosts: {}".format(hostnames)


#https://www.zabbix.com/documentation/2.2/manual/appendix/api/template/get
Esempio n. 22
0
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
from zabbix.api import ZabbixAPI
import zabbix_cli

args = zabbix_cli.zabbix_arg_parse()
# Create ZabbixAPI class instance
try:
    zapi = ZabbixAPI(url=args.api_url,
                     user=args.username,
                     password=args.password)
except:
    sys.exit("Zabbix API is not available")
else:
    print("Zabbix API is ready")
    zapi.do_request("user.logout", {})
    try:
        zapi = ZabbixAPI(url=zabbix_url, user=zabbix_user, password=zabbix_password)
    except Exception as e:
        print e, 'ZabbixAPI: Authenticate failed.'
        exit (-1)

    # Get Zabbix API version
    try:
        result_version = zapi.api_version()
    except:
        result_version = "2.4"

    # Hostgroup create
    hostgroup = system_name
    try:
        result_hostgroup = zapi.do_request('hostgroup.get', { 'filter': {'name': hostgroup}})
        if not result_hostgroup['result']:
            result_hostgroup = zapi.do_request('hostgroup.create', {'name': hostgroup})
            hostgroup_id = result_hostgroup['result']['groupids'][0]
        else:
            hostgroup_id = result_hostgroup['result'][0]['groupid']
    except Exception as e:
        print e, 'ZabbixAPI: Hostgroup exist failed.'
        exit (-1)

    # Host create
    hostname = system_domain
    try:
        result_host = zapi.do_request('host.get', { 'filter': {'name': hostname}})
        result_template = zapi.do_request('template.get', { 'filter': {'host': zabbix_template}})
        if not result_host['result']:
class ZabbixTemplates:
    def __init__(self, _url, _user, _password):
        self.zapi = ZabbixAPI(url=_url, user=_user, password=_password)

    def exportTemplates(self, args):
        export = {
            'templates': {
                'method': 'template.get',
                'id': 'templateid',
                'name': 'host'
            },
            'groups': {
                'method': 'hostgroup.get',
                'id': 'groupid',
                'name': 'name'
            },
            'valueMaps': {
                'method': 'valuemap.get',
                'id': 'valuemapid'
            },
            'hosts': {
                'method': 'host.get',
                'id': 'hostid'
            },
            'screens': {
                'method': 'screen.get',
                'id': 'screenid'
            },
            'maps': {
                'method': 'map.get',
                'id': 'sysmapid'
            },
            'images': {
                'method': 'image.get',
                'id': 'imageid'
            },
        }

        request_args = {"output": "extend"}

        if args.templates != 'All':
            request_args.filter = {"host": [args.templates]}

        for key in export:
            print "LALALA"
            result = self.zapi.do_request(export[key]['method'], request_args)
            if not result['result']:
                print "No matching host found for '{}'".format(hostname)
                exit(-3)

            if result['result']:
                for t in result['result']:
                    pprint(t)
                    if False == os.path.isdir(args.out_dir + '/' + key):
                        os.mkdir(args.out_dir + '/' + key)
                    dest = args.out_dir + '/' + key + '/' + t['name'] + '.xml'
                    self.exportTemplate(t[export[key]['id']], dest, key)

    def exportTemplate(self, tid, oput, export):

        print "tempalteid:", tid, " output:", oput
        args = {"options": {export: [tid]}, "format": "xml"}

        result = self.zapi.do_request('configuration.export', args)
        template = xml.dom.minidom.parseString(
            result['result'].encode('utf-8'))
        date = template.getElementsByTagName("date")[0]
        # We are backing these up to git, steralize date so it doesn't appear to change
        # each time we export the templates
        date.firstChild.replaceWholeText('2016-01-01T01:01:01Z')
        f = open(oput, 'w+')
        f.write(template.toprettyxml().encode('utf-8'))
        f.close()
Esempio n. 25
0
ZABBIX_SERVER = 'http://localhost/zabbix'
ZABBIX_USER = '******'
ZABBIX_PASSWORD = '******'

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Delete host from Zabbix server')
    parser.add_argument('-n',
                        '--hostname',
                        required=True,
                        help='Zabbix hostname')
    args = parser.parse_args()

    zapi = ZabbixAPI(url=ZABBIX_SERVER,
                     user=ZABBIX_USER,
                     password=ZABBIX_PASSWORD)
    """Get hostid by hostname"""
    result = zapi.do_request('host.get', {
        'filter': {
            'host': [args.hostname]
        },
        'output': ['name', 'hostid']
    })

    if not result['result']:
        sys.exit('hostname not found')
    """Delete host from Zabbix server"""
    hostid = result['result'][0]['hostid']
    result = zapi.do_request('host.delete', [hostid])
    print(result)
Esempio n. 26
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. 27
0
class ZabbixReader():
    """ Read data from Zabbix monitoring system"""
    def __init__(self, _url, _user, _password):
        url = _url
        user = _user
        password = _password

        try:
            self.zapi = ZabbixAPI(url=url, user=user, password=password)
        except Exception as e:
            print 'Error in creating connection to Zabbix Api (%s)' % (url)
            raise Exception(e)

        self.metric_names_regex = [
            '^(?P<metric_name>ICMP loss).*',
            '^(?P<metric_name>ICMP ping).*',
            '^(?P<metric_name>ICMP response time).*',
            '^(?P<metric_name>Incoming traffic) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Outgoing traffic) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>In utilization) on (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Out utilization) on (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Inbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Outbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Percentage inbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Percentage outbound errors) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Incoming unicast packets) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Outcoming unicast packets) on interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*',
            '^(?P<metric_name>Admin status) of interface (?P<interface>\S+) \(CORP-(?P<location>\S+)[-_]{1}LINKID.*'
            ### ip sla pattern 1
            ,
            '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>0)-|1-(?P<tos>0)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>0)-|1-(?P<tos>0)-).*',
            '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>0)-|1-(?P<tos>0)-).*',
            '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>96)-|1-(?P<tos>96)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>96)-|1-(?P<tos>96)-).*',
            '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>96)-|1-(?P<tos>96)-).*',
            '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>128)-|1-(?P<tos>128)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>128)-|1-(?P<tos>128)-).*',
            '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>128)-|1-(?P<tos>128)-).*',
            '^(?P<metric_name>Jitter) for CORP-.* (?:IBM-(?P<tos1>184)-|1-(?P<tos>184)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.* (?:IBM-(?P<tos1>184)-|1-(?P<tos>184)-).*',
            '^(?P<metric_name>Packet loss) for CORP.* (?:IBM-(?P<tos1>184)-|1-(?P<tos>184)-).*'
            ### ip sla pattern 2
            ,
            '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>0)-|-(?P<tos>0)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>0)-|-(?P<tos>0)-).*',
            '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>0)-|-(?P<tos>0)-).*',
            '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>96)-|-(?P<tos>96)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>96)-|-(?P<tos>96)-).*',
            '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>96)-|-(?P<tos>96)-).*',
            '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>128)-|-(?P<tos>128)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>128)-|-(?P<tos>128)-).*',
            '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>128)-|-(?P<tos>128)-).*',
            '^(?P<metric_name>Jitter) for CORP-.*(?:IBM-(?P<tos1>184)-|-(?P<tos>184)-).*',
            '^(?P<metric_name>Packet Delay) for CORP-.*(?:IBM-(?P<tos1>184)-|-(?P<tos>184)-).*',
            '^(?P<metric_name>Packet loss) for CORP.*(?:IBM-(?P<tos1>184)-|-(?P<tos>184)-).*'
        ]

    def get_stats_from_hname_json(self, _hname):
        """ Gets all items stats from defined hname """
        host_groups = self.get_gnames_from_hname(_hname)
        print "Start get stats for hname: %s" % (_hname)
        results = []
        iobjects = self.get_iobj_from_hname(_hname)
        print "Start stats for hname [%s]" % (_hname)
        for item in iobjects:
            tags = self.parseNameToTags(item['key_'], item['name'])
            if tags is None:
                continue
            metric_name = tags['metric_name']
            interface = tags['interface']
            location = tags['location']
            tos = tags['tos']
            if len(location) == 0:
                location = self.getLocationFromHostName(_hname)
            for history in self.get_stats_for_iid(item['itemid'],
                                                  item['value_type']):
                # parse history based on data type
                # 0 - numeric float, 3 - numeric unsigned
                if item['value_type'] in ['0', '3']:
                    value = float(history['value'])
                else:
                    value = history['value']
                json_body = {
                    "measurement": "zabbix_data",
                    "tags": {
                        "client": str(host_groups),
                        "device": _hname,
                        "interface": interface,
                        "location": location,
                        "tos": tos,
                        "itemid": history['itemid']
                    },
                    "time": int(history['clock']),
                    "fields": {
                        metric_name: value
                    }
                }
                print json_body
                results.append(json_body)
        to_return = json.dumps(results)
        return to_return

    def get_stats_from_gname_json(self, _gname):
        """ Gets all items stats from defined gname
            return json with statistics
        """

        client_devices = self.get_hnames_from_gname(_gname)
        print "Start get stats for gname [%s], hosts: %s" % (_gname,
                                                             client_devices)
        results = []
        for device in client_devices:
            iobjects = self.get_iobj_from_hname(device)
            print "Start stats for hname [%s]" % (device)
            for item in iobjects:
                tags = self.parseNameToTags(item['key_'], item['name'])
                if tags is None:
                    continue
                metric_name = tags['metric_name']
                interface = tags['interface']
                location = tags['location']
                tos = tags['tos']
                if len(location) == 0:
                    location = self.getLocationFromHostName(device)
                for history in self.get_stats_for_iid(item['itemid'],
                                                      item['value_type']):

                    # parse history based on data type
                    # 0 - numeric float, 3 - numeric unsigned
                    if item['value_type'] in ['0', '3']:
                        value = float(history['value'])
                    else:
                        value = history['value']
                    json_body = {
                        "measurement": "zabbix_data",
                        "tags": {
                            "client": _gname,
                            "device": device,
                            "interface": interface,
                            "location": location,
                            "tos": tos,
                            "itemid": history['itemid']
                        },
                        "time": int(history['clock']),
                        "fields": {
                            metric_name: value
                        }
                    }
                    print json_body
                    results.append(json_body)
        to_return = json.dumps(results)
        return to_return

    def get_gnames_from_hname(self, _hname):
        """ Get gnames [] from host name """
        hid = self.get_hid_from_hname(_hname)
        result_groups = self.zapi.do_request('hostgroup.get', {"hostids": hid})
        group_names = [group['name'] for group in result_groups['result']]
        return group_names

    def get_iobj_from_hname(self, _host_name):
        """ Gets items ids [] from host defined by name """
        hostid = self.get_hid_from_hname(_host_name)
        result_items = self.zapi.do_request('item.get', {
            "hostids": hostid,
            "output": "extend",
            "sortfield": "name"
        })
        return result_items['result']

    def get_stats_for_iid(self, _iid, _value_type, _limit=5):
        """ Gets history data for specific item defined by id"""
        result_hist_item = self.zapi.do_request(
            'history.get', {
                "output": "extend",
                "history": _value_type,
                "itemids": _iid,
                "sortfield": "clock",
                "sortorder": "DESC",
                "limit": _limit
            })
        return result_hist_item['result']

    def get_iids_from_hname(self, _host_name):
        """ Gets items ids [] from host defined by name """
        hostid = self.get_hid_from_hname(_host_name)
        result_items = self.zapi.do_request('item.get', {
            "hostids": hostid,
            "output": "extend",
            "sortfield": "name"
        })
        return [items['itemid'] for items in result_items['result']]

    def get_inames_from_hname(self, _host_name):
        """ Gets items names [] from host defined by name """
        hostid = self.get_hid_from_hname(_host_name)
        result_items = self.zapi.do_request('item.get', {
            "hostids": hostid,
            "output": "extend",
            "sortfield": "name"
        })
        return [items['name'] for items in result_items['result']]

    def get_hid_from_hname(self, _host_name):
        """ Get host id (unicode) from host name """
        result_hosts = self.zapi.do_request('host.get',
                                            {"filter": {
                                                "name": _host_name
                                            }})
        host_id = [host['hostid'] for host in result_hosts['result']]
        return host_id[0]

    def get_hids_from_gname(self, _group_name):
        """ Get hosts ids [] from group defined by name """
        gid = self.get_gid_from_gname(_group_name)
        result_hosts_in_group = self.zapi.do_request('host.get',
                                                     {"groupids": gid})
        return [hosts['hostid'] for hosts in result_hosts_in_group['result']]

    def get_hnames_from_gname(self, _group_name):
        """ Get hosts names [] from group defined by name """
        gid = self.get_gid_from_gname(_group_name)
        result_hosts_in_group = self.zapi.do_request('host.get',
                                                     {"groupids": gid})
        return [hosts['name'] for hosts in result_hosts_in_group['result']]

    def get_gid_from_gname(self, _group_name):
        """ Get group id (unicode) from group name """
        result_groups = self.zapi.do_request('hostgroup.get',
                                             {"filter": {
                                                 "name": _group_name
                                             }})
        group_id = [group['groupid'] for group in result_groups['result']]
        return group_id[0]

    def parseVariableInItemName(self, _ikey, _iname):
        """ Change item name based on algorithm and variable value
	    	Sample item name: Out Traffic $1 Warsaw 
	    	Action: $1 should be replace with param nr 1 from key_ (key_=keyname[param1, param2,...])
	    """

        var_num = ''
        param = ''
        new_name = '?'

        # looking for variable in item name (ex. $1, $2...)
        var_match = re.search('.*\$([1-9]){1}.*', _iname)
        print 'var_match: ', var_match

        # if variable not exist do nothing with name
        if var_match is None:
            return _iname

        # read variable value
        try:
            var_num = int(var_match.group(1))
        except:
            # do nothing if there is no group 1 matched - value not readable
            return _iname

        # get param from key[var_num]
        key_match = re.search('.*\[(.*)]', _ikey)
        if key_match is None:
            param = '???'
        try:
            param = key_match.group(1).split(',')[var_num -
                                                  1]  # list starts from 0
        except Exception as e:
            print e
            param = '????'

        # replace $var_num with key param number var_num
        to_replace = '$' + str(var_num)
        new_name = _iname.replace(to_replace, param)
        return new_name

    def parseNameToTags(self, _ikey, _iname):

        tag_dic = {
            'metric_name': '',
            'interface': '',
            'location': '',
            'tos': ''
        }
        metric_name = self.parseVariableInItemName(_ikey, _iname)
        print 'key: ', _ikey, 'name: ', _iname
        print 'metric name: ', metric_name
        for metric_regex in self.metric_names_regex:
            match = re.search(metric_regex, metric_name)

            if match is not None:
                print 'Metric name in regex: ', metric_regex
                try:
                    print 'group metric_name: %s' % match.group(
                        'metric_name')  # metric_name
                    tag_dic['metric_name'] = match.group('metric_name')
                except IndexError as ie:
                    print 'Error in metric name: group number invalid'
                    print ie
                try:
                    print 'group interface: %s' % match.group(
                        'interface')  # interface
                    print 'group location: %s' % match.group(
                        'location')  # location
                    tag_dic['interface'] = match.group('interface')
                    tag_dic['location'] = match.group('location')
                except IndexError as ie:
                    print 'No interface or location: group number invalid'
                    print ie
                try:
                    if match.group('tos') is not None:
                        tag_dic['tos'] = self.mapTOSToName(match.group('tos'))
                    if match.group('tos1') is not None:
                        tag_dic['tos'] = self.mapTOSToName(match.group('tos1'))
                    print 'group [tos]: %s' % tag_dic['tos']
                except:
                    pass
                break
        if match is None:
            print 'METRIC: %s do not match any pattern' % metric_name
            return None

        return tag_dic

    def getLocationFromHostName(self, _hname):
        """ gets name for metric which don't have name """

        # get all items names from hname
        metric_names = self.get_inames_from_hname(_hname)

        # looking for location name
        location = ''
        for metric_name in metric_names:
            for metric_regex in self.metric_names_regex:
                match = re.search(metric_regex, metric_name)
                if match is not None:
                    try:
                        location = match.group('location')
                    except IndexError as ie:
                        pass
                    else:
                        return location
                else:
                    print 'TAG::location not set for %s' % _hname
            return location

    def mapTOSToName(self, _tos):
        """ Maps TOS to user friendly name """
        qos_name_dic = {
            '184': 'RT-Voice',
            '128': 'BC2',
            '96': 'BC1',
            '0': 'BE'
        }
        print 'Passed qos name: ', qos_name_dic.get(_tos)
        return qos_name_dic.get(_tos)
Esempio n. 28
0
# simple parse for arguments
url = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
zhost = sys.argv[4]
csvHostGroups = sys.argv[5]
print "Going to connect to {} as {}".format(url,user)
print ("Will try to update zabbix hostgroups for {} with groups: {}".format(zhost,csvHostGroups))


# Create ZabbixAPI class instance
use_older_authenticate_method = False
zapi = ZabbixAPI(url, use_older_authenticate_method, user, password)

zversion = zapi.do_request('apiinfo.version')
print "Zabbix API version: {}".format(zversion['result'])


# first need to resolve the list of hostgroup names to proper ids
candidateGroupIds=[]
candidateGroups=csvHostGroups.split(",")
for candidateGroup in candidateGroups:
  print("Trying to resolve hostgroup: {}".format(candidateGroup))
  hostgroupResults = zapi.do_request('hostgroup.get', {'filter': { 'name': [ candidateGroup ]  } })
  #print("result {}, count {}".format( hostgroupResults['result'], len(hostgroupResults['result'])  ))
  if len(hostgroupResults['result'])==0:
    print("ERROR could not resolve hostgroup to id, does not exist")
    exit(2)
  else:
    print("hostgroup {} resolves to id {}".format( candidateGroup, hostgroupResults['result'][0]['groupid'] ))
Esempio n. 29
0
    default='')
parser.add_argument(
    '--force',
    dest='force',
    help=
    "if template update is failed then existing template will be deleted and new template will be created with the same name.",
    required=False,
    action='store_true')
parser.add_argument(dest='arg1',
                    nargs=1,
                    help='provide file or directory name',
                    metavar='path')
args = parser.parse_args()

try:
    zapi = ZabbixAPI(url=args.api_url,
                     user=args.username,
                     password=args.password)
except ZabbixAPIException as err:
    sys.exit(err.data)
else:
    path = args.arg1[0]
    if os.path.isdir(path):
        import_dir_with_templates(path)
    elif os.path.isfile(path):
        import_single_template(path)
    else:
        sys.exit("{0} is not a valid template or directory".format(path))

    zapi.do_request('user.logout')
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)
def main():
    # read the file into a string
    try:
        file = open (args.file, "r")
        data=file.read()
    except Exception as e:
        raise e

    zapi = ZabbixAPI(os.environ['ZABBIX_URL'], user=os.environ['ZABBIX_USERNAME'], password=os.environ['ZABBIX_PASSWORD'])

    if args.json:
        import_format='json'
    else:
        import_format='xml'

    zapi.do_request(
        'configuration.import',
        {
            "format": import_format,
            "rules": {
                "applications": {
                    "createMissing": True,
                    "deleteMissing": True
                },
                "discoveryRules": {
                    "createMissing": True,
                    "updateExisting": True,
                    "deleteMissing": True
                },
                "graphs": {
                    "createMissing": True,
                    "updateExisting": True,
                    "deleteMissing": True
                },
                "groups": {
                    "createMissing": True
                },
                "hosts": {
                    "createMissing": True,
                    "updateExisting": True
                },
                "httptests": {
                    "createMissing": True,
                    "updateExisting": True,
                    "deleteMissing": True
                },
                "images": {
                    "createMissing": False,
                    "updateExisting": False
                },
                "items": {
                    "createMissing": True,
                    "updateExisting": True,
                    "deleteMissing": True
                },
                "maps": {
                    "createMissing": False,
                    "updateExisting": False
                },
                "screens": {
                    "createMissing": False,
                    "updateExisting": False
                },
                "templateLinkage": {
                    "createMissing": True,
                    # supported from 4.4? "deleteMissing": True
                },
                "templates": {
                    "createMissing": True,
                    "updateExisting": True
                },
                "templateScreens": {
                    "createMissing": True,
                    "updateExisting": True,
                    "deleteMissing": True
                },
                "triggers": {
                    "createMissing": True,
                    "updateExisting": True,
                    "deleteMissing": True
                },
                "valueMaps": {
                    "createMissing": True,
                    "updateExisting": True
                }
            },
            "source": data
        }
    )
Esempio n. 32
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)
    # Create ZabbixAPI class instance
    try:
        zapi = ZabbixAPI(url=zabbix_url, user=zabbix_user, password=zabbix_password)
    except Exception, e:
        print e, 'ZabbixAPI: Authenticate failed.'

    # Get Zabbix API version
    try:
        result_version = zapi.api_version()
    except:
        result_version = "2.4"

    # Hostgroup get
    hostgroup = system_name
    try:
        result_hostgroup = zapi.do_request('hostgroup.get', { 'filter': {'name': hostgroup}})
        if not result_hostgroup['result']:
            print 'Can not be found host group ' + hostgroup
            exit (-1)
        else:
            hostgroup_id = result_hostgroup['result'][0]['groupid']
    except Exception, e:
        print e, 'ZabbixAPI: hostgroup.get exist failed.'

    # Host get
    hostname = system_domain
    try:
        result_host = zapi.do_request('host.get', { 'filter': {'name': hostname}})
        if not result_host['result']:
            print 'Can not be found host ' + hostname
            exit (-1)
Esempio n. 34
0
                          'hostid': webTestId,
                          'description': service_name + ' is down',
                          'expression': '{' + zhost + ':web.test.fail[' + service_name + '].max(#3)}=1',
                          'priority': tpriority
                  })
    return trigRes


"""
################# MAIN ######################################3

# Create ZabbixAPI class instance
use_older_authenticate_method = False
zapi = ZabbixAPI(url, use_older_authenticate_method, user, password)

zversion = zapi.do_request('apiinfo.version')
print("Zabbix API version: {}".format(zversion['result']))
version_number = zversion['result']
# API func changed from 2.x to 3.x
zfunc = "httptest" if version_number > "2." else "webcheck"

# Get or create test host
print("============host creation===================")
hostRes = zabbix_get_host(zhost)
# only want single host operations
hostid = 0
if len(hostRes['result']) > 1:
    print("This operation is only meant for single hosts.")
    exit(1)
elif len(hostRes['result']) == 1:
    hostid = hostRes['result'][0]['hostid']
Esempio n. 35
0
import logging
from zabbix.api import ZabbixAPI

logging.basicConfig(level = logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logger = logging.getLogger(__name__)

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

t1 = z.host.getobjects(status=1})
t2 = z.do_request('host.getobjects', {'status':1})

[host['host'] for host in t1]
[host['host'] for host in t2['result']]
Esempio n. 36
0
  sys.exit(1)

# simple parse for arguments
url = sys.argv[1]
user = sys.argv[2]
password = sys.argv[3]
host = sys.argv[4]
key = sys.argv[5]
print "Going to connect to {} as {}, and retrieve from host {} the item {}".format(url,user,host,key)


# Create ZabbixAPI class instance
use_older_authenticate_method = False
zapi = ZabbixAPI(url, use_older_authenticate_method, user, password)

zversion = zapi.do_request('apiinfo.version')
print "Zabbix API version: {}".format(zversion['result'])


# https://www.zabbix.com/documentation/2.2/manual/api/reference/host/get
# Get specified host
print "----------------------------"
thehost = zapi.do_request('host.get',
                          {
                              'filter': {'host': host},
                              'selectItems' : 'extend',
                              'output': 'extend'
                          })
if len(thehost['result'])<1:
  print "HALTING. There was no host defined in zabbix with id: {}".format(host)
  sys.exit(2)