Beispiel #1
0
def get(user, password, template, url):
    zabbix = ZabbixAPI(url=url, user=user, password=password)
    f = zabbix.do_request('template.get', {'filter': {'host': template},'output': 'templateid'})
    templateid = f['result'][0]['templateid']
    item = zabbix.do_request('item.get',{'templateids': templateid,'output': 'extend'})
    for n in item['result']:
         dict_item.update({ n['name']: n['key_']})
    triggers = zabbix.do_request('trigger.get',{'templateids': templateid,'output': 'extend'})
    for n in triggers['result']:
        dict_trigger.update({ n['triggerid']: n['description']})
    zabbix.user.logout()
Beispiel #2
0
def get_hostids_from_zbx():
    '''Достаем из базы все IP, для которых zbx-hostid еще неизвестен и опрашиваем заббикс для них'''
    global dbname
    global use_zabbix
    if not use_zabbix:
        return
    with sqlite3.connect(dbname) as con:
        con.row_factory = sqlite3.Row
        # SELECT all IPs, which have no hostid associated
        result = con.execute(
            "SELECT ip FROM arp WHERE ip NOT IN (SELECT ip FROM zbxhosts WHERE hostid is NOT NULL)"
        )
        if result:
            z = ZabbixAPI(url=cfg['zabbix']['zbx_url'],
                          user=cfg['zabbix']['username'],
                          password=cfg['zabbix']['password'])
            for i, row in enumerate(result):
                hostid = zabbix.get_hostid_by_ip(z_api=z, ip=row['ip'])
                if not hostid:
                    print('Cant find host id for ' + row['ip'])
                    continue
                con.execute(
                    "INSERT INTO zbxhosts (ip, hostid) values ('{ip}', '{hostid}')"
                    .format(ip=row['ip'], hostid=hostid))
                progress(i, 'Add hostids from zabbix to database')
            print()
def zbx_connect(config, env):
     ''' connect to zabbix API
     '''
     mode_verbose = config["default"]["mode_verbose"]

     zbx_url = config[env]["zbx_url"]
     if mode_verbose:
          logging.info("zabbix URL = %s" % zbx_url)
     zbx_usr = config[env]["zbx_usr"]
     zbx_pwd = config[env]["zbx_pwd"]

     zapi = ZabbixAPI(url=zbx_url,user=zbx_usr,password=zbx_pwd)

     if mode_verbose:
         logging.info("connection zabbix API version = %s " % zapi.api_version())

     return zapi
Beispiel #4
0
def main():
    """main function that accepts arguemnts, runs the program and connects to zabbix server"""

    parser = argparse.ArgumentParser(
        description='Get information about systemd processes'
    )  ##gets argument(filename)
    parser.add_argument("host", type=str, help="addresss of zabbix server")
    parser.add_argument("user", type=str, help="zabbix user for login")
    parser.add_argument("password", type=str, help="zabbix user password")
    args = parser.parse_args()

    global zabb

    try:
        zabb = ZabbixAPI()
        zapi = ZabbixAPI(args.host, user=args.user, password=args.password)
        zapi.timeout = 5.1

    except ZabbixAPIException as e:
        sys.stderr.write(e)
        sys.exit(1)
    #except :
    #sys.stderr.write("Unexpected error:"+str(sys.exc_info()[0]))
    #sys.exit(1)

    host_name = 'Zabbix server'
    hosts = zapi.host.get(filter={"host": host_name},
                          selectInterfaces=["interfaceid"])
    if hosts:
        host_id = hosts[0]["hostid"]

    master_item_id = create_master_item(host_id, hosts, zapi)

    processes, information_parameters = get_service_names_and_parameters(
        zapi,
        "/etc/zabbix/zabbix_agentd.d/boyans_service_monitoring/service_status.ini"
    )

    for process in processes:
        print(process)
        exit_code_zac = add_application(host_id, process, zapi)
        if (exit_code_zac != -2):
            add_items_to_application(host_id, process, zapi, exit_code_zac,
                                     hosts, master_item_id,
                                     information_parameters)
Beispiel #5
0
    def __init__(self, server, user, password, verify=True):
        """
        Init zabbix class for further needs
        :param user: string
        :param password: string
        :return: pyzabbix object
        """
        self.server = server
        self.user = user
        self.password = password
        # Enable HTTP auth
        s = requests.Session()
        s.auth = (user, password)

        self.zapi = ZabbixAPI(server, s)
        self.zapi.session.verify = verify
        self.zapi.login(user, password)
        self.version = self.get_version()
Beispiel #6
0
    def __init__(self, idc='qc'):
        qc_url = ''
        xg_url = ''
        qc_auth = ''
        xg_auth = ''
        self.url = qc_url if idc == 'qc' else xg_url
        self.auth = qc_auth if idc == 'qc' else xg_auth

        self.z = ZabbixAPI(url=self.url, use_auth=True, auth=self.auth)
Beispiel #7
0
def is_credentials_valid(**kwargs):
    try:
        zapi = ZabbixAPI(**kwargs)
        sleep(0.1)
        if not zapi.user.logout():
            pass
        return True
    except ZabbixAPIException:
        return False
    def zaebitrix(zname, rdata):
        user = "******"
        password = "******"

        url = 'https://zabbix.homecredit.ru'
        z = ZabbixAPI(url=url, user=user, password=password)

        packet = [ZabbixMetric('intranet.homecredit.ru', zname, rdata)]

        result = ZabbixSender(zabbix_server='10.6.141.33',
                              use_config=False).send(packet)
        print(result)
        logout = z.user.logout()
Beispiel #9
0
def main():
    # config acesso
    data = config()

    # Cria ZabbixAPI class instance
    zabiixAPI = ZabbixAPI(url=data['zabbix']['host'],
                          user=data['zabbix']['user'],
                          password=data['zabbix']['pwd'])

    host1, host2 = hostname(zabiixAPI)

    print(host1)
    print("\n")
    print(host2)
Beispiel #10
0
    def component_execute(self):
        with ZabbixAPI(url=self.url.value,
                       user=self.username.value,
                       password=self.password.value) as zabbix:
            # Gets all of the items for the given host
            # noinspection PyTypeChecker
            api_items = zabbix.do_request(
                "item.get", {
                    "output": "extend",
                    "filter": {
                        "host": [self.host.value]
                    },
                    "sortfield": "name"
                })
            # Converts the items into an internal representation
            self.items.value = []
            # Stores a mapping between id and item
            mapping = {}
            for item in api_items["result"]:
                newItem = ZabbixItem(item)
                self.items.value.append(newItem)
                mapping[newItem.itemid] = newItem

            # Gets the value history for each item
            # noinspection PyTypeChecker
            history = zabbix.do_request(
                "history.get", {
                    "output": "extend",
                    "history": 0,
                    "itemids": [item.itemid for item in self.items.value],
                    "sortfield": "clock",
                    "sortorder": "DESC",
                    "limit": self.history_count.value * len(self.items.value)
                })

            # Adds the history to each item
            for historyValue in history["result"]:
                item = mapping[historyValue["itemid"]]
                if item.value_type == '0':  # Numeric Float
                    item.value_history.append(FloatHistory(historyValue))
                elif item.value_type == '1':  # Character
                    item.value_history.append(StringHistory(historyValue))
                elif item.value_type == '2':  # Log
                    item.value_history.append(LogHistory(historyValue))
                elif item.value_type == '3':  # Numeric unsigned (int)
                    item.value_history.append(IntegerHistory(historyValue))
                elif item.value_type == '4':  # Text
                    item.value_history.append(TextHistory(historyValue))
    def __init__(self):
        super().__init__()

        # Initiate vPoller
        try:
            self._vpoller = vPollerAPI(
                vpoller_endpoint=vfzsync.CONFIG["vpoller"]["endpoint"])
            self._vpoller.run(method="about",
                              vc_host=vfzsync.CONFIG["vpoller"]["vc_host"])
        except vPollerException:
            message = "vPoller initialization failed"
            logger.exception(message)
            raise vPollerException(message)

        # Initiate FNT API
        try:
            self._command = FNTCommandAPI(
                url=vfzsync.CONFIG["command"]["url"],
                username=vfzsync.CONFIG["command"]["username"],
                password=vfzsync.CONFIG["command"]["password"],
            )
        except FNTNotAuthorized:
            message = "FNT Command authorization failed"
            logger.exception(message)
            raise FNTNotAuthorized(message)

        # Initiate ZabbixAPI
        try:
            self._zapi = ZabbixAPI(
                url=vfzsync.CONFIG["zabbix"]["url"],
                user=vfzsync.CONFIG["zabbix"]["username"],
                password=vfzsync.CONFIG["zabbix"]["password"],
            )
            self._zapi.session.verify = False
            zabbix_hostgroup_name = vfzsync.CONFIG["zabbix"]["hostgroup"]
            zabbix_hostgroup_id = get_zabbix_hostgroupid_by_name(
                self._zapi, zabbix_hostgroup_name)
            if not zabbix_hostgroup_id:
                zabbix_hostgroup_id = self._zapi.hostgroup.create(
                    name=zabbix_hostgroup_name)
                logger.info(
                    f"Created Zabbix host group {zabbix_hostgroup_name}.")

        except ZabbixAPIException:
            message = "Zabbix authorization failed"
            logger.exception(message)
            raise ZabbixAPIException(message)
Beispiel #12
0
def add_monitor(hostname, url=config.XG_URL, auth=config.XG_AUTH):
    try:
        zabbix_api = ZabbixAPI(url=url, use_auth=True, auth=auth)
        hosts_id = zabbix_api.do_request('host.get', params={'output':'hostid', 'filter':{'host':[hostname]}})

        if url==config.XG_URL:
            zabbix_api.do_request('host.massadd', params={'hosts': hosts_id['result'],
                            'templates': config.XG_TEMPLATE_IDS})
        else:
            zabbix_api.do_request('host.massadd', params={'hosts': hosts_id['result'],
                            'templates': config.QC_TEMPLATE_IDS})
    except Exception,e:
        pass
def get_host_from_db(cur, conf_yaml, node_ip, conn_):
    try:
        with ZabbixAPI(url=conf_yaml['api']['server'],
                       user=conf_yaml['api']['user'],
                       password=conf_yaml['api']['password']) as zabbix_api:
            result2 = zabbix_api.do_request(
                'item.get',
                dict(output=['itemid'],
                     search=dict(key_="syslog", type=2, status=0)))
            items = []
            host_node = dict()
            for res in result2['result']:
                items.append(res['itemid'])
            result1 = zabbix_api.do_request(
                'host.get', dict(itemids=items, output=['hostid', 'host']))
            for res in result1['result']:
                host_node.update(
                    {res['hostid']: dict(name=res['host'], ip=None)})
            result3 = zabbix_api.do_request(
                'hostinterface.get',
                dict(output=['ip', 'hostid'], hostids=[*host_node.keys()]))
            for res in result3['result']:
                if res['hostid'] in host_node:
                    host_node[res['hostid']]['ip'] = res['ip']
            try:
                if not search_ex_in_dict(host_node, 'ip', node_ip):
                    raise AddressValueError(node_ip)
            except AddressValueError:
                logger.exception(
                    'На адресе:::' + node_ip +
                    ':::Не настроен syslog элемент данных в zabbix')
                sys.exit(1)
            for h in host_node:
                ins_sql = (datetime.datetime.now(), h, host_node[h]['ip'],
                           host_node[h]['name'])
                sql_ = """INSERT INTO 'zabbix_hosts' ('update_time','hostid', 'ip', 'hostname')
                             VALUES (?,?,?,?)"""
                cur.execute(sql_, ins_sql)
                conn_.commit()
    except KeyError:
        logger.exception('Ошибка В параметрах конфигурации')
        sys.exit(1)
    return None
Beispiel #14
0
    def __init__(self, config=None):
        """Create an instance of the plugin."""
        super(Zabbix, self).__init__(config)

        if config is None:
            config = {}

        self.api_url = config.get('api', DEFAULT_API)
        self.defcon = config.get('defcon', 1)
        self.level = config.get('severity', None)

        username = config.get('username', None)
        password = config.get('password', None)
        hostgroups = config.get('hostgroups', None)

        if not config:
            return

        self.zapi = ZabbixAPI(url=self.api_url,
                              user=username,
                              password=password)
        self.f = {}
        self.time = datetime.datetime.now().isoformat()
        self.proxy = config.get('proxy', None)
        if self.proxy:
            for proxy in self.zapi.proxy.get(monitored_hosts=1,
                                             output='extend'):
                if proxy['host'] == self.proxy:
                    self.proxyid = proxy['proxyid']
                    self.f['proxy_hostid'] = self.proxyid
        if hostgroups:
            self.groups = []
            g = {
                a['name']: a['groupid']
                for a in self.zapi.hostgroup.get(output=['name', 'groupid'])
            }
            try:
                for group in hostgroups:
                    self.groups.append(g[group])
            except KeyError:
                pass
Beispiel #15
0
def main():
    zabbix_conn = ZabbixAPI(url="http://librenms.bm.compute.strln.net/zabbix",
                            user=username,
                            password=get_pass_from_sm(username))

    for host in zabbix_conn.host.get():
        hosts_list.append(host["host"])
    if host_to_add in hosts_list:
        print("Host {} exists".format(host_to_add))
    else:
        zabbix_conn.host.create(host=host_to_add,
                                name=host_to_add,
                                status=0, #Host status - Enabled
                                interfaces=[{
                                    'interfaceid': '2', #ID of the interface.
                                    'main': '1', #Whether the interface is used as default on the host. Only one interface of some type can be set as default on a host. 
                                    'type': '2', #Interface type. 2 - SNMP
                                    'useip': '0', #Whether the connection should be made via IP. 0 - connect using host DNS name; 
                                    'ip': '', #IP address used by the interface. Can be empty if the connection is made via DNS.
                                    'dns': host_to_add, #DNS host address
                                    'port': '161', #SNMP port
                                    'bulk': '1' #Whether to use bulk SNMP requests. 
                                }],
                                groups=[{
                                    "groupid": "15" #UCS group
                                }],
                                templates=[{
                                    "templateid": "10278" #Template Module Interfaces Simple SNMPv3
                                }, {
                                    "templateid": "10280" #Template UCS SNMPv3 Vethernet interfaces
                                }, {
                                    "templateid": "10389" #Template Module Interfaces Error SNMPv3
                                }])
        print("Host {} is added".format(host_to_add))

        

    zabbix_conn.user.logout()
Beispiel #16
0
def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('-H', required=True, metavar='Hostname')
    parser.add_argument('-I', required=True, metavar='Item Name')
    parser.add_argument('-f', required=True, metavar='From Timestamp')
    parser.add_argument('-t', required=True, metavar='Till Timestamp')

    args = parser.parse_args()


    zapi = ZabbixAPI(url=zabbixServer, user=zabbixUser, password=zabbixPass)

    fromTimestamp = int(time.mktime(datetime.datetime.strptime(args.f, "%d/%m/%Y %H:%M").timetuple()))
    tillTimestamp = int(time.mktime(datetime.datetime.strptime(args.t, "%d/%m/%Y %H:%M").timetuple()))
    

    f  = {  'name' : args.I  }
    items = zapi.item.get(filter=f, host=args.H, output='extend' )

    with open(filename,'w') as csvFile:
        csvHeader = ['date','current connections']
        writer = csv.writer(csvFile)
        writer.writerow(csvHeader)

        for item in items:
            #print("ItemID: {} - Item: {} - Key: {}".format(item['itemid'], item['name'], item['key_']))

            values = zapi.history.get(itemids=item['itemid'], time_from=fromTimestamp, time_till=tillTimestamp, history=item['value_type'])

            for historyValue in values:
                currentDate = datetime.datetime.fromtimestamp(int(historyValue['clock'])).strftime('%d/%m/%Y %H:%M:%S')

                #print("{} {} Value: {}".format(historyValue['clock'], currentDate, historyValue['value']))
                myData = [currentDate, historyValue['value']]
                writer.writerow(myData)
    csvFile.close()
    print("create csv finished")
 def __init__(self, sHostName, sZabbixIP, iZabbixPort, sZabUser, sZabPwd):
     """
     sHostName is a name of host or array (HOST.HOST) IN ZABBIX
     *Zab* are parameters for Zabbix connection.
     """
     # oLog.debug("Entered GeneralZabbix.__init__")
     self.sZabbixURL = 'http://' + sZabbixIP + "/zabbix"
     self.sZabbixIP = sZabbixIP
     self.iZabbixPort = iZabbixPort
     self.dApplicationNamesToIds = {}
     self.sHostName = sHostName
     self.ldApplications = []
     self.dItemNames = {}
     self.dAppIds = {}
     self.dApps = {}
     # self.sArrayName = sHostName
     self.sHostID = ''
     self.iHostID = 0
     try:
         self.oZapi = ZabbixAPI(url=self.sZabbixURL, user=sZabUser, password=sZabPwd)
         self.oAPI = self.oZapi
         self.oZSend = ZabbixSender(zabbix_server=self.sZabbixIP, zabbix_port=self.iZabbixPort)
         lsHosts = self.oZapi.host.get(filter={"host": sHostName})
         if len(lsHosts) > 0:
             # Just use the first host
             self.sHostID = str(lsHosts[0]['hostid'])
             self.iHostID = int(self.sHostID)
             oLog.debug("host ID of host {1}: {0}".format(self.sHostID, self.sHostName))
         else:
             oLog.error("Invalid or non-existent host in Zabbix")
             raise ZabInterfaceException("This host '{}' isn't known to Zabbix".format(sHostName))
     except ZabbixAPIException as e:
         oLog.error("Cannot connect to Zabbix API")
         oLog.error(str(e))
         raise ZabInterfaceException
     return
def ack():
    eventid = int(unquote(request.args['eventid']).replace("'", ''))
    taskid = request.args['taskid']
    action = app.config['ACTION']
    #login to zabbix
    zapi = ZabbixAPI(url=app.config['URL'],
                     user=app.config['USER'],
                     password=app.config['PWD'])
    #acknowledge alert
    zapi.do_request(
        'event.acknowledge', {
            'eventids': eventid,
            'action': action,
            'message':
            'ServiceNow has created {} for this alert'.format(taskid)
        })
    #logut zabbix
    zapi.do_request('user.logout')
    return 'ok'
def others_defs():
    # Get API Version
    # To simplify API versioning, since Zabbix 2.0.4, the version of the API matches the version of Zabbix itself.
    print(zapi.api_version())  # zapi.apiinfo.version()
    print(zapi.do_request('apiinfo.version'))
    # Get item id with a item name
    print(zapi.get_id("item", item='Free memory'))


if __name__ == '__main__':
    ZABBIX_URL = 'https://localhost/zabbix'
    ZABBIX_USER = '******'
    ZABBIX_PASSWORD = '******'

    # Create ZabbixAPI class instance
    with ZabbixAPI(url=ZABBIX_URL, user=ZABBIX_USER, password=ZABBIX_PASSWORD) as zapi:

        # zapi.host.get(output=["host"]) --> zapi.do_request("host.get", params={"output":['host']})
        # Impl: pyzabbix.api.ZabbixAPI.__getattr__()
        # https://www.zabbix.com/documentation/4.0/manual/api/reference/host/get
        host_list = zapi.host.get(
            output=["host"],  # output="extend",
            selectInterfaces=["ip"],  # not mandatory
            status=0,
        )

        for host in host_list:  # type: dict
            print(host)
            host_name = host.get("host")
            host_id = host.get("hostid")
            print(host_name, get_free_memory())
import time

from pyzabbix.api import ZabbixAPI
from pyzabbix import ZabbixMetric, ZabbixSender

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

zapi = ZabbixAPI(url='https://REPLACE WITH U ZBX IP\DNS DUDE',
                 user='******',
                 password='******')

options = webdriver.ChromeOptions()
#options.add_argument('--headless')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')

driver = webdriver.Remote(
    command_executor='http://REPLACE WITH U IP DUDE:4444/wd/hub',
    desired_capabilities=DesiredCapabilities.CHROME,
    options=options)

driver.get("https://REPLACE WITH U IP DUDE/login")

username = driver.find_element_by_id('user')
username.clear()
username.send_keys('REPLACE WITH U USER DUDE')

password = driver.find_element_by_id('password')
password.clear()
Beispiel #21
0
            # on the last iteration we will add link between dev5 and dev4
            eselement1 = sorted_transit_list[i - 1] # i-1 is the first device during first iteration
            eselement2 = sorted_transit_list[i]     # this is the second one during first iteration

            tmp = {
                'selementid1': devices[eselement1]['id_on_map'],
                'selementid2': devices[eselement2]['id_on_map'],
                'color': '00FF00'
            }
            if tmp not in links: 
                links.append(tmp)

    gv_list = ['"'+item+'"' for item in sorted_transit_list]  
    graph = ' -> '.join(gv_list)
    dot.write(graph + '\n')

dot.write('}')
dot.close()

if use_zabbix:
    z_api = ZabbixAPI(url=cfg['zabbix']['zbx_url'], user=cfg['zabbix']['username'], password=cfg['zabbix']['password'])
    zabbix.create_or_update_map(z_api=z_api,
        mapname=cfg['zabbix']['mapname'], 
        selements=selements, 
        links=links, 
        mwidth=x+100, 
        mheight=max_height)
else:
    print('Check map in ' + cfg['zabbix']['mapname'] + '.gv')
print('Done')
Beispiel #22
0
 def api_connect(self, username, password):
     self.__api = ZabbixAPI(url=self.__url,
                            user=username,
                            password=password)
Beispiel #23
0
def transfer_data():
    def get_latest_timestamp(kafka_topic):
        latest_timestamp = 0

        topic_partition = TopicPartition(
            topic=kafka_topic,
            partition=0,
        )
        end_offset = consumer.end_offsets([topic_partition])[topic_partition]

        if end_offset > 0:
            # partition  assigned after poll, and we could seek
            consumer.poll(5, 1)
            consumer.seek(topic_partition, end_offset - 1)
            message = consumer.poll(10000, 500)
            msgs = message[topic_partition]

            if len(msgs) > 0:
                record = msgs[-1]
                latest_timestamp = record.timestamp / 1000.0
        return latest_timestamp

    try:
        producer = KafkaProducer(
            bootstrap_servers=bootstrap_servers,
            client_id=client_id,
            retries=-1,
            acks=1,
            request_timeout_ms=600000,
            api_version=(1, 0, 0),
            compression_type='lz4',
            security_protocol=security_protocol,
            ssl_context=ssl_context,
            ssl_check_hostname=ssl_check_hostname,
            ssl_cafile=ssl_cafile,
            ssl_certfile=ssl_certfile,
            ssl_keyfile=ssl_keyfile,
            ssl_password=ssl_password,
            value_serializer=lambda m: json.dumps(m).encode('utf-8'))

        consumer = KafkaConsumer(
            kafka_topic,
            api_version=(1, 0, 0),
            value_deserializer=lambda m: json.loads(m.decode('utf-8')),
            session_timeout_ms=600000,
            security_protocol=security_protocol,
            ssl_context=ssl_context,
            ssl_check_hostname=ssl_check_hostname,
            ssl_cafile=ssl_cafile,
            ssl_certfile=ssl_certfile,
            ssl_keyfile=ssl_keyfile,
            ssl_password=ssl_password,
            bootstrap_servers=bootstrap_servers)

        zapi = ZabbixAPI(
            url="%s/api_jsonrpc.php" % zabbix_host,
            user=zabbix_login,
            password=zabbix_passwd,
        )
        log.info("Zabbix API version: " + str(zapi.api_version()))

        latest_timestamp = get_latest_timestamp(kafka_topic)

        tz = pytz.timezone('Europe/Moscow')

        log.info("Latest timestamp from kafka: %s" %
                 datetime.fromtimestamp(latest_timestamp, tz=tz))

        # Get all monitored hosts
        hosts = zapi.host.get(monitored_hosts=1,
                              selectGroups="extend",
                              output=["hostid", "groups", "name"])

        hosts_chunked = chunks(hosts, 10)

        sended = 0

        for hosts_chunk in hosts_chunked:
            h_ids = list(h['hostid'] for h in hosts_chunk)

            items = zapi.item.get({
                "hostids": h_ids,
                "monitored": True,
                "output": [
                    "itemid",
                    "hostid",
                    "name",
                ],
            })

            items_chunked = chunks(items, 10)

            for items_chunk in items_chunked:

                i_ids = list(i['itemid'] for i in items_chunk)

                current_history = zapi.history.get(
                    history=0,
                    time_from=int(latest_timestamp),
                    # time_till=int(latest_timestamp + 60),
                    hostids=h_ids,
                    itemids=i_ids,
                    sortfield="clock",
                    sortorder="DESC",
                    output=["itemid", "value", "clock"])

                log.debug(current_history)

                for h_item in current_history:
                    host_id = [
                        h['hostid'] for h in items_chunk
                        if h['itemid'] == h_item['itemid']
                    ][-1]

                    groups_list = [
                        h['groups'] for h in hosts_chunk
                        if h['hostid'] == host_id
                    ]

                    groups = [g['name'] for g in groups_list[0]]

                    host_name = [
                        h['name'] for h in hosts_chunk
                        if h['hostid'] == host_id
                    ][-1]

                    item_name = [
                        h['name'] for h in items_chunk
                        if h['itemid'] == h_item['itemid']
                    ][-1]

                    result = {
                        "host_id": host_id,
                        "item_id": h_item['itemid'],
                        "value": h_item['value'],
                        "clock": h_item['clock'],
                        "metric_name": item_name,
                        "group": groups,
                        "host_name": host_name,
                        "zabbix_host": zabbix_host,
                        "zabbix_name": zabbix_name
                    }

                    log.debug(result)
                    producer.send(kafka_topic, result)
                    sended += 1

        log.info("Pushed %s metrics" % sended)
        log.info("Last item time: %s" %
                 datetime.fromtimestamp(int(result['clock']), tz=tz))

    except KafkaError as ex:
        # Decide what to do if produce request failed...
        log.exception(ex)
    except Exception as ex:
        # Do not break the loop
        log.exception(ex)
class GeneralZabbix:
    def __init__(self, sHostName, sZabbixIP, iZabbixPort, sZabUser, sZabPwd):
        """
        sHostName is a name of host or array (HOST.HOST) IN ZABBIX
        *Zab* are parameters for Zabbix connection.
        """
        # oLog.debug("Entered GeneralZabbix.__init__")
        self.sZabbixURL = 'http://' + sZabbixIP + "/zabbix"
        self.sZabbixIP = sZabbixIP
        self.iZabbixPort = iZabbixPort
        self.dApplicationNamesToIds = {}
        self.sHostName = sHostName
        self.ldApplications = []
        self.dItemNames = {}
        self.dAppIds = {}
        self.dApps = {}
        # self.sArrayName = sHostName
        self.sHostID = ''
        self.iHostID = 0
        try:
            self.oZapi = ZabbixAPI(url=self.sZabbixURL, user=sZabUser, password=sZabPwd)
            self.oAPI = self.oZapi
            self.oZSend = ZabbixSender(zabbix_server=self.sZabbixIP, zabbix_port=self.iZabbixPort)
            lsHosts = self.oZapi.host.get(filter={"host": sHostName})
            if len(lsHosts) > 0:
                # Just use the first host
                self.sHostID = str(lsHosts[0]['hostid'])
                self.iHostID = int(self.sHostID)
                oLog.debug("host ID of host {1}: {0}".format(self.sHostID, self.sHostName))
            else:
                oLog.error("Invalid or non-existent host in Zabbix")
                raise ZabInterfaceException("This host '{}' isn't known to Zabbix".format(sHostName))
        except ZabbixAPIException as e:
            oLog.error("Cannot connect to Zabbix API")
            oLog.error(str(e))
            raise ZabInterfaceException
        return

    def __fillApplications__(self, reFilter=None):
        # receive the list of applications
        ldApplications = self.oZapi.do_request('application.get', {'hostids': self.sHostID})
        ldAppResult = ldApplications['result']
        dBuf = {}
        if len(ldAppResult) == 0:
            # the host exists but didn't return anything, just continue
            oLog.info("Array with ID {0} and name {1} doesn't answer".format(self.sHostID, self.sHostName))
        else:
            # oLog.debug("Applications on host {0}: {1}".format(self.sArrayName, ldAppResult))
            # now filter the apps list for this host
            for dApp in ldAppResult:
                sAppName = dApp['name']
                if reFilter:
                    if reFilter.match(sAppName):
                        dBuf[sAppName] = dApp['applicationid']
                        # oLog.debug('__fillApplications__: found app {}'.format(sAppName))
                    else:
                        # oLog.debug("__fillApplications__: skipped app {}".format(sAppName))
                        pass
                else:
                    dBuf[sAppName] = dApp['applicationid']
            self.dApplicationNamesToIds = dBuf
        return

    def _oPrepareZabMetric(self, sAppName, sParameter, iValue):
        """Prepare ZabbixMetric instance for sending to a Zabbix server"""
        dFilter = {'name': sAppName + ' ' + sParameter}
        try:
            iAppID = self.dApplicationNamesToIds[sAppName]
            dItem2Get = {'hostids': self.sHostID,
                         'applicationids': iAppID,
                         'filter': dFilter,
                         'sort': 'name'}
            dResult = self.oZapi.do_request('item.get', dItem2Get)
            try:
                sKey = dResult['result'][0]['key_']
                # now we have key, so we can prepare data to Zabbix
                oRet = ZabbixMetric(host=self.sHostName, key=sKey, value=iValue)
            except IndexError:
                oLog.info("Can't receive item named '{}' from Zabbix with item.get".format(dFilter['name']))
                oRet = None
        except KeyError:
            oLog.info('Unknown application name "{}"'.format(sAppName))
            # oLog.info('Known apps: ' + str(self.dApplicationNamesToIds))
            oRet = None
        return oRet

    def _SendMetrics(self, loMetrics):
        """Send only non-empty metrics to Zabbix"""
        if loMetrics:
            # skip empty objects from loMetrics
            loMetrics = [o for o in loMetrics if o is not None]
            self.oZSend.send(loMetrics)
        else:
            pass   # dont send empty metrics
        return

    def _iGetHostID(self):
        return int(self.sHostID)

    def _sName(self):
        return self.sHostName

    def _bHasApplication(self, sAppName):
        sAppName = sAppName.lower()
        ldApplications = self.oZapi.do_request('application.get', {'hostids': self.sHostID})
        for dApp in ldApplications['result']:
            sNewName = dApp['name'].lower()
            sNewID = dApp['applicationid']
            self.dAppIds[sNewName] = dApp['applicationid']
            self.dApps[sNewID] = ZabbixApplication(sNewName, self, dApp)
        bRet = (sAppName in self.dAppIds)
        return bRet

    def _bHasItem(self, sItemName):
        bRet = False
        sItemName = sItemName.lower()
        if sItemName in self.dItemNames:
            bRet = True
        else:
            # try to refresh dItemNames
            dGetItem = {'hostids': self.iHostID,
                        'search': {'name': sItemName}}
            dItems = self.oAPI.do_request('item.get', dGetItem)
            # oLog.debug('_bHasItem: result of item.get() is {}'.format(str(dItems)))
            if len(dItems['result']) > 0:
                # matching item(s) found
                for dItemDict in dItems['result']:
                    # dItemDict = dItems['result'][0]
                    # oLog.debug("Item found: {}".format(str(dItemDict)))
                    sName = dItemDict['name'].lower()
                    dItemDict['key'] = dItemDict.get('key_')    # from the Zabbix parameter 'key_'
                    self.dItemNames[sName] = ZabbixItem(sName, self, dItemDict)
                bRet = True
            else:
                # No item found
                bRet = False
            # oLog.debug('_bHasItem: dItemNames after call is: ' + str(self.dItemNames))
        return bRet

    def _oGetItem(self, sItemName):
        """returns item object by name"""
        sItemName = sItemName.lower()
        if self._bHasItem(sItemName):
            return self.dItemNames.get(sItemName, None)
        else:
            return None

    def _oGetApp(self, sAppName):
        sAppName = sAppName.lower()
        if self._bHasApplication(sAppName):
            return self.dApps[self.dAppIds[sAppName]]
        else:
            return None

    def _oAddApp(self, sAppName):
        # sAppName = sAppName.lower()
        if self._bHasApplication(sAppName):
            # already have this app
            oApp = self._oGetApp(sAppName)
        else:
            oApp = ZabbixApplication(sAppName, self)
            oApp._NewApp(sAppName)
            self.dAppIds[sAppName] = oApp._iGetID
            self.dApps[oApp._iGetID] = oApp
        return oApp

    def _oAddItem(self, sItemName, sAppName='', dParams=None):
        # sItemName = sItemName.lower()
        if self._bHasItem(sItemName):
            # already have that item
            oItem = self._oGetItem(sItemName)
            oLog.debug('Already have that item, returned {}'.format(str(oItem)))
        else:
            # need to create item
            oItem = ZabbixItem(sItemName, self, dParams)
            self.dItemNames[sItemName] = oItem
            if sAppName != '':
                oApp = self._oGetApp(sAppName)
                oItem._LinkWithApp(oApp)
            oItem._NewZbxItem()
            oLog.debug('Created a new item, returned {}'.format(str(oItem)))
        return oItem

    def _MakeTimeStamp(self):
        """make an application and item (if there are no), send current timestamp as a TS of last update"""
        sTSAppName = 'Timestamps'
        sItemName = 'Last updated'
        if not self._bHasApplication(sTSAppName):
            self._oAddApp(sTSAppName)
        if self._bHasItem(sItemName):
            oTimeStamp_Item = self._oGetItem(sItemName)
            oLog.debug('Timestamp item: ' + str(oTimeStamp_Item))
        else:
            oTimeStamp_Item = self._oAddItem(
                sItemName, sAppName=sTSAppName,
                dParams={'key': "Update_Time", 'value_type': 3, 'units': 'unixtime',
                         'description': 'Date and time of last data update'})
        # now the application and item must exist
        oTimeStamp_Item._SendValue(int(time.time()), self.oZSend)
        oLog.debug('TimeStamp set!')
        return

    def _SendInfoToZabbix(self, sArrayName, ldInfo):
        """send data to Zabbix via API"""
        loMetrics = []
        # oLog.debug('sendInfoToZabbix: data to send: {}'.format(str(ldInfo)))
        for dInfo in ldInfo:
            if self.sAppClass == 'System':   # Special case
                sAppName = self.sAppClass
            else:
                sAppName = (self.sAppClass + ' ' + dInfo['name']).strip()
            for sName, oValue in dInfo.items():
                try:
                    loMetrics.append(self.dOperations[sName](sAppName, oValue))
                except KeyError:
                    # unknown names passed
                    oLog.info('Skipped unknown information item named {} with value {}'.format(
                        sName, str(oValue)))
                    pass
        self._SendMetrics(loMetrics)
        return
Beispiel #25
0
                    "interface": {
                        "ip": proxy_ip,
                        "dns": "",
                        "useip": "1",
                        "port": "10051"
                    },
                    "hosts": host_ids
                })
        else:
            # если создан обновляем список хостов
            zapi.do_request(
                'proxy.update', {
                    "proxyid": zbx_proxies[proxy_name_templ + proxy_name],
                    "hosts": host_ids
                })


if __name__ == '__main__':
    conf_path = 'conf.yaml'
    conf = get_config(conf_path)
    logger = get_logger(conf['logger'])
    zapi = ZabbixAPI(url=conf['zabbix']['url'],
                     user=conf['zabbix']['user'],
                     password=conf['zabbix']['password'])
    logger.debug('Debug mode')
    hosts_res = get_hosts(conf['hosts_file_path'])
    src_groups = list(hosts_res.keys())
    zbx_groups = sync_zbx_groups(zapi, src_groups)
    sync_hosts = sync_zbx_hosts(zapi, hosts_res, zbx_groups)
    sync_zbx_proxy(zapi, sync_hosts, conf['proxy_name_templ'])
Beispiel #26
0
class Zabbix_Api:
    def __init__(self, idc='qc'):
        qc_url = ''
        xg_url = ''
        qc_auth = ''
        xg_auth = ''
        self.url = qc_url if idc == 'qc' else xg_url
        self.auth = qc_auth if idc == 'qc' else xg_auth

        self.z = ZabbixAPI(url=self.url, use_auth=True, auth=self.auth)

    def Get_Token(self, user=None, password=None):
        try:
            token = self.z._login(user=user, password=password)
            return token
        except Exception as e:
            print(e)

    # 获取id,支持扩展获取所有id
    def Get_ID(self,
               HostName=None,
               Template=None,
               ScreenName=None,
               Action='filter',
               Macros_Flag=False,
               Filter_Flag=False):
        if HostName and len(HostName) <= 6:
            exit('Warning: Hostname so short')
        if HostName and '*' in HostName:
            HostName = ''.join(HostName.split('*'))
            Filter_Flag = True

        Get_Input = HostName or Template or ScreenName
        Host_List = []
        Host_ID = []
        Template_List = []
        Template_ID = []
        Screen_ID = []
        Screen_List = []
        try:
            for l in Get_Input.split(','):
                if HostName:
                    Host_List.append(l)
                elif Template:
                    Template_List.append(l)
                elif ScreenName:
                    Screen_List.append(l)
            if Host_List:
                # 模糊匹配与精确查询
                Action = 'search' if Filter_Flag else Action
                # Group_Flag = True if GroupName else Group_Flag
                for h in Host_List:
                    host_id = self.z.do_request('host.get',
                                                params={'output': ['host', 'hostid'], "%s" % Action: {'host': h}})
                    res = sorted(host_id['result'], key=lambda x: int(x['host'].split('-')[-1]))
                    for i in res:
                        del i['host']
                        Host_ID.append(i)
                return Host_ID

            elif Template_List:
                for t in Template_List:
                    if Macros_Flag:
                        re = self.z.do_request('template.get',
                                               params={'selectMacros': ['macro', 'value'], 'filter': {'host': t}})
                        macros = re['result'][0]['macros']
                        for i in macros:
                            i.pop('hosts')
                        data = re['result']
                        Template_ID.extend(data)
                    re = self.z.do_request('template.get', params={'output': 'templateid', 'filter': {'host': t}})
                    data = re['result']
                    Template_ID.extend(data)
                return Template_ID
            elif Screen_List:
                for s in Screen_List:
                    re = self.z.do_request('screen.get', params={'output': 'screenid', 'filter': {'name': s}})
                    Screen_ID.append(re['result'][0]['screenid'])
                return Screen_ID

        except Exception as e:
            print(e)

    def Get_GroupID(self, GroupName=None):
        try:
            Group_ID = self.z.do_request('hostgroup.get', params={'output': 'extend', 'filter': {'name': GroupName}})
            return Group_ID['result'][0]['groupid']
        except Exception as e:
            print(e)

    def Get_GraphID(self, HostName=None, GraphName=None, Columns=3):
        Graph_ID = []
        Graph_List = []
        x = 0
        y = 0
        try:
            Host_ID = self.Get_ID(HostName=HostName)
            Only_Host_ID = map(lambda x: x.values()[0], Host_ID)
            for hostid in Only_Host_ID:
                re_graphid = self.z.do_request('graph.get',
                                               params={'output': ['graphid'],
                                                       'hostids': hostid,
                                                       'softfield': 'graphid', 'search': {'name': GraphName}})
                if re_graphid['result']:
                    Graph_ID.append(re_graphid['result'][0]['graphid'])
                else:
                    exit('Some host not have the graph: "%s" !' % GraphName)
            for graph in Graph_ID:
                Graph_List.append({
                    'resourcetype': '0',
                    'resourceid': graph,
                    'width': '500',
                    'height': '200',
                    'x': str(x),
                    'y': str(y),
                    'colspan': '0',
                    'rowspan': '0',
                    'elements': '0',
                    'valign': '0',
                    'halign': '0',
                    'style': '0',
                    'url': '',
                    'dynamic': '0'
                })
                x += 1
                if x == int(Columns):
                    x = 0
                    y += 1
            return Graph_ID, Graph_List
        except Exception as e:
            print(e)

    def Screen_Create(self, HostName=None, GraphName=None, ScreenName=None, Columns=3):
        try:
            Graph_ID, Graph_List = self.Get_GraphID(HostName=HostName, GraphName=GraphName)
            if len(Graph_ID) % Columns == 0:
                vsize = len(Graph_ID) / Columns
            else:
                vsize = (len(Graph_ID) / Columns) + 1

            Screen_ID = self.Get_ID(ScreenName=ScreenName)[0]
            if Screen_ID:
                re = self.z.do_request('screen.update', params={'screenid': Screen_ID,
                                                                'name': ScreenName,
                                                                'screenitems': Graph_List,
                                                                'hsize': Columns,
                                                                'vsize': vsize})
                if re['result']['screenids']:
                    print('The screen : "%s" has been update!' % ScreenName)
            else:
                re = self.z.do_request('screen.create',
                                       params={'name': ScreenName, 'hsize': Columns, 'vsize': vsize,
                                               'screenitems': Graph_List})
                if re['result']['screenids']:
                    print('The screen name: "%s" create succeed!' % ScreenName)
                    sys.exit(0)
                exit('Screen create failed')
        except Exception as e:
            print(e)

    def Create_Template(self, TemplateName=None, LinkTemplate=None, Template_ID=None, Macros=None):
        try:
            if LinkTemplate:
                Template_Info = self.Get_ID(Template=LinkTemplate, Macros_Flag=True)[0]
                Template_ID = Template_Info['templateid']
                Macros = Template_Info['macros']
            re = self.z.do_request('template.create',
                                   params={'host': TemplateName, 'groups': {'groupid': 1},
                                           'templates': Template_ID,
                                           'macros': Macros})
            if re['result']['templateids']:
                print('Template "%s" create succeed!' % TemplateName)
        except Exception as e:
            print(e)

    def Delete_Template(self, TemplateName=None):
        Template_List = []
        try:
            Template_ID = self.Get_ID(Template=TemplateName)[0]['templateid']
            Template_List.append(Template_ID)
            re = self.z.do_request('template.delete', params=Template_List)
            if re['result']['templateids']:
                print('Template "%s" has been delete!' % TemplateName)
        except Exception as e:
            print(e)

    def Mass_Remove_Templates(self, HostName=None, Templates=None):
        data = []
        try:
            Host_ID = self.Get_ID(HostName=HostName)
            Only_Host_ID = map(lambda x: x.values()[0], Host_ID)
            for t in Templates.split(','):
                Template_ID = self.Get_ID(Template=t)[0]['templateid']
                re = self.z.do_request('host.massremove',
                                       params={'hostids': Only_Host_ID, 'templateids_clear': Template_ID})
                data.append(re['result'])
            if data:
                print('template has been unlink!')
                sys.exit(0)
            exit('template unlink failure!')
        except Exception as e:
            print(e)

    def Mass_Add_Templates(self, HostName=None, Templates=None):
        Templates_List = []
        data = []
        try:
            Host_ID = self.Get_ID(HostName=HostName)
            for t in Templates.split(','):
                Templates_ID = self.Get_ID(Template=t)
                Templates_List.extend(Templates_ID)
                re = self.z.do_request('host.massadd', params={'hosts': Host_ID, 'templates': Templates_List})
                data.append(re['result'])
            if data:
                print('Template has been link!')
                sys.exit(0)
            exit('Template link failure!')
        except Exception as e:
            print(e)

    def Mass_Groups(self, HostName=None, GroupName=None, Method=None):
        Group_ID = self.Get_GroupID(GroupName=GroupName)
        Hosts_ID = self.Get_ID(HostName=HostName)
        Only_Host_ID = map(lambda x: x.values()[0], Hosts_ID)
        Mass = 'host.mass'
        try:
            if Method == 'replace':
                Method = Mass + 'update'
            elif Method == 'add':
                Method = Mass + 'add'
            re = self.z.do_request(Method, params={'hosts': Hosts_ID, 'groups': [{'groupid': Group_ID}]})
            if re['result']['hostids']:
                print('hosts information has been updated!')
            elif Method == 'remove':
                re = self.z.do_request('host.massremove', params={'hostids': Only_Host_ID, 'groupids': Group_ID})
                if re['result']['hostids']:
                    print('hosts information has been updated!')

        except Exception as e:
            print(e)

    def Method(self, ScreenName=None):
        try:
            Screen_ID = self.Get_ID(ScreenName=ScreenName)
            re = self.z.do_request('screen.delete', params=Screen_ID)['result']['screenids']
            if re:
                print('%s has been delete' % ScreenName)
                sys.exit(0)
            print('The given screen name: "%s" not exists' % ScreenName)
        except Exception as e:
            print(e)

    def Disable_Host(self, HostName=None, Method=None):
        status = 0
        data = []
        try:
            status = 1 if Method == 'disable' else status
            Hostids = self.Get_ID(HostName=HostName)
            if not Hostids:
                exit('"%s" not exists!' % HostName)
            for h in Hostids:
                re = self.z.do_request('host.massupdate', params={'hosts': h, 'status': status})
                data.append(re['result']['hostids'])
            if not data:
                exit('"%s" failed!' % Method)
            print('hosts has been "%s" !' % Method)
        except Exception as e:
            print(e)

    def main(self):
        if len(sys.argv) == 1:
            parse.print_help()
        else:
            args = parse.parse_args()
            Method = ['delete', 'disable', 'enable', 'replace', 'remove', 'add', 'create']
            # print(args)
            if args.idc == 'xg':
                self.__init__(idc='xg')
            if args.method_link == 'unlink' and args.template and args.hostname:
                self.Mass_Remove_Templates(HostName=args.hostname, Templates=args.template)
            elif args.method_link == 'link' and args.template and args.hostname:
                self.Mass_Add_Templates(HostName=args.hostname, Templates=args.template)
            elif args.screen and args.hostname and args.graph:
                self.Screen_Create(HostName=args.hostname, GraphName=args.graph, ScreenName=args.screen)
            elif args.graph and args.hostname:
                self.Get_GraphID(HostName=args.hostname, GraphName=args.graph)
            elif args.method:
                if args.screen and args.method in Method:
                    self.Method(ScreenName=args.screen)
                elif args.group and args.hostname and args.method in Method:
                    self.Mass_Groups(HostName=args.hostname, GroupName=args.group, Method=args.method)
                elif args.method == 'create' and args.template or args.link_template:
                    self.Create_Template(TemplateName=args.template, LinkTemplate=args.link_template)
                elif args.method == 'delete' and args.template:
                    self.Delete_Template(TemplateName=args.template)
                elif args.hostname and args.method in Method:
                    self.Disable_Host(HostName=args.hostname, Method=args.method)
            elif args.hostname or args.template:
                re = self.Get_ID(HostName=args.hostname, Template=args.template)
                print(re)
from datetime import datetime, timedelta
import json

zabbix = {}
with open('conf.json', 'r') as confs:
    zabbix = json.loads(confs.read())

timeFrom = "01/01/2020 00:00:00"
timeTill = "31/01/2020 23:59:59"

fromTimestamp = time.mktime(datetime.strptime(timeFrom, "%d/%m/%Y %H:%M:%S").timetuple())
tillTimestamp = time.mktime(datetime.strptime(timeTill, "%d/%m/%Y %H:%M:%S").timetuple())


try:
    zapi = ZabbixAPI(url=zabbix['url'], user=zabbix['username'], password=zabbix['password'])
    print ('Auth Ok!')
except Exception as err:
    print('Erro ao conectar ao Zabbix')
    print('Erro: {}'.format(err))


hostgroup = 'SICI'


getHostGroup = zapi.do_request('hostgroup.get',
                            {
                                "output": "extend",
                                "filter": {
                                    "name": [
                                        hostgroup
Beispiel #28
0
from datetime import datetime, timedelta
import json

zabbix = {}
with open('conf.json', 'r') as confs:
    zabbix = json.loads(confs.read())

timeFrom = "01/01/2020 00:00:00"
timeTill = "31/01/2020 23:59:59"

fromTimestamp = time.mktime(datetime.strptime(timeFrom, "%d/%m/%Y %H:%M:%S").timetuple())
tillTimestamp = time.mktime(datetime.strptime(timeTill, "%d/%m/%Y %H:%M:%S").timetuple())


try:
    zapi = ZabbixAPI(url=zabbix['url'], user=zabbix['username'], password=zabbix['password'])
    print ('Auth Ok!')
except Exception as err:
    print('Erro ao conectar ao Zabbix')
    print('Erro: {}'.format(err))


hostgroup = 'SICI'


getHostGroup = zapi.do_request('hostgroup.get',
                            {
                                "output": "extend",
                                "filter": {
                                    "name": [
                                        hostgroup
Beispiel #29
0
def main():

    changed = False

    module = AnsibleModule(supports_check_mode=False,
                           argument_spec={
                               "url": {
                                   "type": "str",
                                   "required": True
                               },
                               "default_password": {
                                   "type": "str",
                                   "required": False,
                                   "default": "zabbix",
                                   "no_log": True
                               },
                               "login_password": {
                                   "type": "str",
                                   "required": True,
                                   "no_log": True
                               },
                               "users": {
                                   "type": "list",
                                   "required": False,
                                   "no_log": False
                               }
                           })

    try:
        zapi = ZabbixAPI(
            **{
                'url': module.params['url'],
                'user': '******',
                'password': module.params['default_password']
            })

        admin_userid = get_userid_by_name(username='******', zapi=zapi)

        change_password(userid=get_userid_by_name('Admin', zapi),
                        new_passwd=module.params['login_password'],
                        zapi=zapi)

        changed = True
        sleep(0.1)
        zapi.user.logout()
    except ZabbixAPIException as e:
        pass

    try:
        zapi = ZabbixAPI(
            **{
                'url': module.params['url'],
                'user': '******',
                'password': module.params['login_password']
            })

        users_list = [
            i["alias"] for i in zapi.do_request("user.get")["result"]
        ]

        for user in module.params['users']:
            if user["name"] not in users_list:
                if not create_user(username=user['name'],
                                   password=user['password'],
                                   user_type=user['type'],
                                   groups=user["groups"],
                                   zapi=zapi):
                    return module.fail_json(msg=e.message, json=e.json)
                else:
                    changed = True
                    users_list = [
                        i["alias"]
                        for i in zapi.do_request("user.get")["result"]
                    ]
                    continue

            if not is_credentials_valid(
                    **{
                        'url': module.params['url'],
                        'user': user['name'],
                        'password': user['password']
                    }):
                changed = True
                change_password(userid=get_userid_by_name(user['name'], zapi),
                                new_passwd=user['password'],
                                zapi=zapi)
                sleep(0.1)

            if not update_user(username=user['name'],
                               password=user['password'],
                               user_type=user['type'],
                               groups=user["groups"],
                               zapi=zapi):
                return module.fail_json(msg=e.message, json=e.json)

        sleep(0.1)
        zapi.user.logout()
    except ZabbixAPIException as e:
        return module.fail_json(msg=e.message, json=e.json)

    result = {"changed": changed}

    module.exit_json(**result)
Beispiel #30
0
import os
from pyzabbix.api import ZabbixAPI

# Create ZabbixAPI class instance
pasted_URL = 'http://' + str(os.environ["MASTER_NODE_IP_PUBLIC"]) + '/zabbix/'
zapi = ZabbixAPI(url=str(pasted_URL), user='******', password='******')

node_name_removed = str(os.environ["NODE_NAME_REMOVED"])

# Get dictionary of host to be deleted
result_removed_host_id = zapi.do_request(
    'host.get', {'filter': {
        'name': [node_name_removed]
    }})

# Get id of host to be deleted
parsed_removed_host_id = result_removed_host_id['result'][0]['hostid']

# Delete node based on its id
result_delete_node = zapi.do_request('host.delete', [parsed_removed_host_id])

# Logout from Zabbix
zapi.user.logout()
class New(Script):
    class Meta:
        name = "Create FTTB CPE w/ automatic uplink selection and monitoring"
        description = "Generate standard CPE router configuration \
                       and configure uplink switch and linkage"

        field_order = [
            'business_name', 'asset_tag', 'uplink_site', 'skip_zabbix',
            'skip_uplink_port', 'confirmation_email', 'comments', 'rack_mount'
        ]

    # ##################Check to make sure you have these defined##############
    RACK_MOUNT_ID = DeviceType.objects.get(model="RB2011-RM").id
    WALL_MOUNT_ID = DeviceType.objects.get(model="RB2011").id
    SITE_ID = Site.objects.get(name="Customer Premise").id
    DEVICE_ROLE_ID = DeviceRole.objects.get(name="CPE").id
    AGG_ROLE_ID = DeviceRole.objects.get(name="Aggregation").id
    PLATFORM_ID = Platform.objects.get(name="RouterOS").id
    CHOICES = ((RACK_MOUNT_ID, "Rack Mount"), (WALL_MOUNT_ID, "Wall Mount"))
    INET_VLAN = VLAN.objects.get(vid=900)
    MGMT_VLAN = VLAN.objects.get(vid=107)
    #SITES = Site.objects.filter(region_id=1)
    REGION = 1
    ZAPI = ZabbixAPI(
        url='http://zabbix-web-apache-mysql:8080/api_jsonrpc.php/',
        user='******',
        password='******')
    SNMP_COMMUNITY = "got"
    # ##################END###################

    rack_mount = ChoiceVar(choices=((True, "Rack Mount"), (False,
                                                           "Wall Mount")))
    business_name = StringVar(label="Business Name")
    asset_tag = StringVar(label="Asset Tag", required=False)
    hardware_choice = ChoiceVar(choices=CHOICES)
    comments = TextVar(label="Comments", required=False)
    uplink_site = ObjectVar(model=Site, query_params={'region_id': REGION})
    skip_zabbix = BooleanVar(label="Disable Zabbix configuration")
    skip_uplink_port = BooleanVar(label="Disable upstream port selection")
    confirmation_email = BooleanVar(label="Send Confirmation Email")

    def run(self, data, commit):
        # Create the device
        device = Device(name=data['business_name'],
                        device_role_id=self.DEVICE_ROLE_ID,
                        device_type_id=data["hardware_choice"],
                        platform_id=self.PLATFORM_ID,
                        site_id=self.SITE_ID)
        device.save()

        interfaces = Interface.objects.filter(device_id=device.id)
        enabled_interfaces = []
        mgmt_intf = interfaces.get(name="b107")
        enabled_interfaces.append(mgmt_intf)
        uplk_intf = interfaces.get(name="ether10")
        enabled_interfaces.append(uplk_intf)
        uplk_intf.mode = "tagged"
        uplk_intf.tagged_vlans.set([self.INET_VLAN, self.MGMT_VLAN])
        uplk_intf.description = "Uplink"
        uplk_intf.save()
        inet_intf = interfaces.get(name="ether1")
        enabled_interfaces.append(inet_intf)
        inet_intf.description = "Internet"
        inet_intf.mode = "access"
        inet_intf.untagged_vlan = self.INET_VLAN
        inet_intf.save()
        mgmt_intf.save()
        for intf in interfaces:
            intf.enabled = False
            intf.save()
        for intf in enabled_interfaces:
            intf.enabled = True
            intf.mtu = 1500
            intf.save()
        available_ip = Prefix.objects.get(
            vlan=self.MGMT_VLAN).get_first_available_ip()
        ip = IPAddress(
            address=available_ip,
            assigned_object_type=ContentType.objects.get_for_model(Interface),
            assigned_object_id=mgmt_intf.id)
        ip.save()
        device.primary_ip4_id = ip.id
        device.primary_ip_id = ip.id
        device.comments = data['comments']
        device.save()

        # ############
        if (not data["skip_zabbix"] and commit):

            # Post to Zabbix API to create host in mikrotik group and ICMP
            # template
            try:
                hostid = self.ZAPI.host.create(
                    host=data["business_name"],
                    interfaces=dict(type=2,
                                    main=1,
                                    useip=1,
                                    ip=available_ip.replace("/24", ""),
                                    port=161,
                                    dns="",
                                    details=dict(
                                        version="1",
                                        bulk="0",
                                        community=self.SNMP_COMMUNITY)),
                    groups=dict(groupid=15),
                    templates=dict(templateid=10186))
                self.log_info("zabbix configured successfully")
            except Exception as e:
                self.log_info("failed to configure zabbix {0}".format(e))

        if (not data["skip_uplink_port"] and commit):
            try:
                agg_switches = Device.objects.filter(
                    site=data["uplink_site"],
                    device_role_id=self.AGG_ROLE_ID,
                    status="active")
                selected_interface = ""
                for agg_switch in agg_switches:
                    interfaces = Interface.objects.filter(
                        device_id=agg_switch.id)
                    for interface in interfaces:
                        if (interface.connection_status is not True
                                and interface.enabled is True
                                and interface.description == ''
                                and interface.type == '1000base-x-sfp'):
                            selected_interface = interface
                            break
                    if selected_interface != "":
                        selected_interface.enabled = True
                        selected_interface.description = device.name
                        selected_interface.mode = "tagged"
                        selected_interface.tagged_vlans.set(
                            [self.INET_VLAN, self.MGMT_VLAN])
                        selected_interface.save()
                        cable = Cable(
                            termination_a=uplk_intf,
                            termination_b=selected_interface,
                        )
                        cable.save()
                        self.log_info(
                            "uplink switch chosen. Port {0} on {1}".format(
                                selected_interface.name, agg_switch.name))
                        break
                if selected_interface == "":
                    self.log_failure("No available aggregate port found. \
                        No aggregate port assigned.")

            except BaseException:
                self.log("failed to document uplink switch")

        self.log_success("Created {0}".format(device.name))
 def login(user, server, password):
     """Login to zabbix server"""
     return ZabbixAPI(user=user, url=server, password=password)
import csv
import sys
from pyzabbix.api import ZabbixAPI

url = input("Type Zabbix URL: ")
login = input("Type login: "******"Type password: "******"hostid", "name", "status"])

print("Hosts in total:", len(hosts))

enriched_hosts = list()

for host in hosts:
    enriched_host = dict()
    enriched_host["name"] = host["name"]
    enriched_host["status"] = host["status"]
    host_id = host["hostid"]
    interfaces = [
        host_interface["ip"]
        for host_interface in zapi.hostinterface.get(hostids=host_id,
                                                     output=["ip"])
    ]
    enriched_host["interfaces"] = interfaces
    groups = [
        host_group["name"]
        for host_group in zapi.hostgroup.get(hostids=host_id, output=["name"])
    ]
Beispiel #34
0
def getmaindata():
    if len(edt_url.get()) == 0:
        onError()
    elif len(edt_login.get()) == 0:
        onError()
    elif len(edt_pass.get()) == 0:
        onError()
    else:
        btn_result.config(text="Get report again!")

        # ======Get server list from file servers.txt==========================
        filename = "servers.txt"
        with open(filename) as f:
            lines = f.read().splitlines()
        # ======Get server list from file servers.txt==========================

        # =======TXT result file=================
        fulldate = datetime.datetime.now()
        month_today = fulldate.strftime("%B")
        datestring = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d_%H-%M-%S')
        resultfile = open('Zabbix_result_' + datestring + '.csv', 'w')
        resultfile_name = resultfile.name

        writer = csv.DictWriter(
            resultfile, fieldnames=["hostname", "Memory avg,%", "Memory max, %", "CPU load avg, %", "CPU load max, %",
                                    "HDD usage %"], delimiter=";")
        writer.writeheader()
        # =======end of TXT result file=================
        url = edt_url.get()
        login = edt_login.get()
        passwd = edt_pass.get()
        
        zapi = ZabbixAPI(url, user=login, password=passwd)
        
        servers = lines
        start_time_human = edt_start_date.get()
        end_time_human = edt_end_date.get()
        
        
        
        
        start_time = round(time.mktime(datetime.datetime.strptime(start_time_human, "%d/%m/%Y").timetuple()))
        end_time = round(time.mktime(datetime.datetime.strptime(end_time_human, "%d/%m/%Y").timetuple()))
        
        

        for hi in zapi.host.get(filter={"host": servers}, output="extend"):
            hid = hi['hostid']
            # print(hi['host'])
            count = 0
            memtotalprc = 0
            cpuloadvaluetotal = 0
            maxmem = 0
            maxcpu = 0
            for ii in zapi.item.get(filter={"hostid": hid}, search={"key_": "vm.memory.size[available]"},
                                    output="extend"):
                zitemid = ii['itemid']

                for hisid in zapi.trend.get(time_from=start_time, time_till=end_time, itemids=zitemid,
                                            output="extend"):

                    zz = zapi.item.get(filter={"hostid": hid}, search={"key_": "vm.memory.size[total]"},
                                       output="extend")
                    #print(zz)
                    memavailsize = int(hisid['value_avg'])
                    memtotalsize = int(zz[0]['lastvalue'])
                    memtotalsizeGB = memtotalsize / 1024 / 1024 / 1024
                    memresult = round(((memtotalsize - memavailsize) / 1024 / 1024 / 1024), 2)
                    memresultprc = round((memresult * 100 / memtotalsizeGB), 2)
                    count = count + 1
                    memtotalprc = memtotalprc + memresultprc
                    zzmemmax = 100 - (((int(hisid['value_min'])) / 1024 / 1024 / 1024) * 100 / memtotalsizeGB)
                    if maxmem <= zzmemmax:
                        maxmem = zzmemmax

            

            for icpu in zapi.item.get(filter={"hostid": hid}, search={"key_": "system.cpu.util[,idle]"},
                                      output="extend"):
                cpuitemid = icpu['itemid']
                for hicpusid in zapi.trend.get(time_from=start_time, time_till=end_time, itemids=cpuitemid,
                                               output="extend"):
                    # print(hicpusid['value'])
                    zzcpumax = hicpusid['value_max']
                    cpuidlevalue = hicpusid['value_avg']
                    cpuloadvalue = round(100 - (float(cpuidlevalue)), 2)
                    cpuloadvaluetotal = cpuloadvaluetotal + cpuloadvalue
                    # print(cpuloadvalue)
                    if maxcpu <= float(zzcpumax):
                        maxcpu = float(zzcpumax)

            for ifs in zapi.item.get(filter={"hostid": hid}, search={"key_": "last-space"}, output="extend"):
                fsvalue = ifs['lastvalue']
                # print(fsvalue)

            print(hi['host'], str(round((memtotalprc / count), 2)), maxmem, (cpuloadvaluetotal / count), maxcpu,
                  fsvalue, sep=';', file=resultfile)

        resultfile.close()
        # =======Excel result file=================
        df = pandas.read_csv(resultfile_name, sep=';')
        df.to_excel('Zabbix_result_' + datestring + '.xlsx', 'Sheet1')
        # =======end of Excel result file=================
        os.remove(resultfile_name)
        # ===========================================
        onEnd()
Beispiel #35
0
        "DNS address of the snmpsim server. Use 'snmpsim' if inside docker network",
        metavar="snmpsim")
    parser.add_argument('--snmpsim-ip',
                        dest="snmpsim_ip",
                        help="IP address of the snmpsim server.",
                        metavar="IP")
    parser.add_argument('--snmpsim-port',
                        dest="snmpsim_port",
                        default="161",
                        help="UDP port of the snmpsim server.",
                        metavar="161")
    args = parser.parse_args()

    try:
        zapi = ZabbixAPI(url=args.api_url,
                         user=args.username,
                         password=args.password)
    except ZabbixAPIException as err:
        print(err.data)

    else:
        path = args.arg1[0]
        if os.path.isdir(path):
            # snmpsim
            snmpsim_create = SnmpsimCreator(path, zapi, args.filter_str,
                                            args.snmpsim_ip, args.snmpsim_dns,
                                            args.snmpsim_port)
            snmpsim_create.scan_snmpsim_root_dir()

            hosts_create = HostsCreator(path, zapi, args.filter_str)
            hosts_create.scan_snmpsim_root_dir()