def main(): '''Hlavni program''' try: zapi = pyzabbix.ZabbixAPI(zbx_url, user=zbx_user, password=zbx_pwd) except Exception as e: print("Nelze se pripojit k Zabbixu. {}".format(e)) return # pp = pprint.PrettyPrinter(indent=2) items = getItems(zapi, zbx_group, zbx_key) if not items: print("Zadne polozky nenalezeny.") return es = Elasticsearch('http://caplan-es.cezdata.corp:80/') if newindex: es.indices.delete(index=es_index, ignore=[400, 404]) es.indices.create(index=es_index, body=index_settings) helpers.bulk(es, getTrends(zapi, items, startstamp, keyname), index=es_index, doc_type=es_type) if verbose > 1: print("Main succesful end.")
def main(args): zapi = pyzabbix.ZabbixAPI('http://%s' % args.zabbix_server) zapi.login(args.zabbix_username, args.zabbix_password) for host in args.host: process(zapi, host)
def __init__(self, base_url, login, password, verify_tls=True, timeout=None, **options): self.options = options self.key_patterns = { prepare_regex(metric['key']): metric for metric in options.get('metrics', []) } self.zapi = pyzabbix.ZabbixAPI(base_url, timeout=timeout) if not verify_tls: import requests.packages.urllib3 as urllib3 urllib3.disable_warnings() self.zapi.session.verify = verify_tls def measure_api_request(r, *args, **kwargs): api_requests_total.inc() api_bytes_total.inc(len(r.content)) api_seconds_total.inc(r.elapsed.total_seconds()) self.zapi.session.hooks = {'response': measure_api_request} self.zapi.login(login, password) self.host_mapping = { row['hostid']: row['name'] for row in self.zapi.host.get(output=['hostid', 'name']) }
def _get_api(self, backend_url, username, password): unsafe_session = QuietSession() unsafe_session.verify = False api = pyzabbix.ZabbixAPI(server=backend_url, session=unsafe_session) api.login(username, password) return api
def get_zabbix_api(self): unsafe_session = QuietSession() unsafe_session.verify = False api = pyzabbix.ZabbixAPI(server=self._settings['server'], session=unsafe_session) api.login(self._settings['username'], self._settings['password']) return api
def get_zabbix_client(astute): url = get_zabbix_url(astute) user, password = get_zabbix_credentials(astute) session = requests.Session() node_cidr = astute['network_scheme']['endpoints']['br-fw-admin']['IP'][0] node_ip = node_cidr.split('/')[0] session.proxies = {'http': 'http://{0}:8888'.format(node_ip)} client = pyzabbix.ZabbixAPI(server=url, session=session) client.login(user=user, password=password) return client
def main(): cfg = config.Config() zapi = pyzabbix.ZabbixAPI() args = parse_args().parse_args() cfg.init(args.config) if args.debug: stream = logging.StreamHandler(sys.stdout) stream.setLevel(logging.DEBUG) log = logging.getLogger("pyzabbix") log.addHandler(stream) log.setLevel(logging.DEBUG) zapi = pyzabbix.ZabbixAPI(cfg.get("zabbix", "uri")) try: zapi.login(cfg.get("zabbix", "user"), cfg.get("zabbix", "password")) except Exception as e: print(e) sys.exit(1) args.func(cfg, args, zapi)
def _login(*args, **kwargs): try: s = requests.Session() s.auth = (CONF.username, CONF.password) s.verify = False conn = pyzabbix.ZabbixAPI(CONF.url, s) #logger.debug("Login to Zabbix (user '%s')" % CONF.username) print("Login to Zabbix (user '%s')" % CONF.username) conn.login(CONF.username, CONF.password) except requests.exceptions.HTTPError: #logger.error("Zabbix authorization failed") print("Zabbix authorization failed") sys.exit(1) #logger.debug("Successfully connected to Zabbix API v%s" % conn.api_version()) return func(conn, *args, **kwargs)
def __init__(self, name, db_uri, zabbix_config): super().__init__() self.name = name self.db_uri = db_uri self.db_hosts_table = "hosts" try: self.db_connection = psycopg2.connect(self.db_uri) # TODO: Test connection? Cursor? except psycopg2.OperationalError as e: logging.error( "Unable to connect to database. Process exiting with error") raise e self.map_dir = zabbix_config["map_dir"] self.zabbix_url = zabbix_config["url"] self.zabbix_username = zabbix_config["username"] self.zabbix_password = zabbix_config["password"] self.dryrun = zabbix_config["dryrun"] self.failsafe = zabbix_config["failsafe"] self.update_interval = 60 self.next_update = None pyzabbix_logger = logging.getLogger("pyzabbix") pyzabbix_logger.setLevel(logging.ERROR) self.api = pyzabbix.ZabbixAPI(self.zabbix_url) try: self.api.login(self.zabbix_username, self.zabbix_password) except pyzabbix.ZabbixAPIException as e: logging.error("Unable to login to Zabbix API: %s", str(e)) raise e logging.info("Connected to Zabbix API version %s", self.api.api_version()) self.property_template_map = utils.read_map_file( os.path.join(self.map_dir, "property_template_map.txt")) self.property_hostgroup_map = utils.read_map_file( os.path.join(self.map_dir, "property_hostgroup_map.txt")) self.siteadmin_hostgroup_map = utils.read_map_file( os.path.join(self.map_dir, "siteadmin_hostgroup_map.txt"))
def __init__(self, name, state, db_uri, zabbix_config): super().__init__(name, state) self.db_uri = db_uri self.db_hosts_table = "hosts" try: self.db_connection = psycopg2.connect(self.db_uri) # TODO: Test connection? Cursor? except psycopg2.OperationalError as e: logging.error( "Unable to connect to database. Process exiting with error") raise exceptions.ZACException(*e.args) self.config = zabbix_config self.update_interval = 60 pyzabbix_logger = logging.getLogger("pyzabbix") pyzabbix_logger.setLevel(logging.ERROR) self.api = pyzabbix.ZabbixAPI(self.config.url) try: self.api.login(self.config.username, self.config.password) except requests.exceptions.ConnectionError as e: logging.error("Error while connecting to Zabbix: %s", self.config.url) raise exceptions.ZACException(*e.args) except (pyzabbix.ZabbixAPIException, requests.exceptions.HTTPError) as e: logging.error("Unable to login to Zabbix API: %s", str(e)) raise exceptions.ZACException(*e.args) self.property_template_map = utils.read_map_file( os.path.join(self.config.map_dir, "property_template_map.txt")) self.property_hostgroup_map = utils.read_map_file( os.path.join(self.config.map_dir, "property_hostgroup_map.txt")) self.siteadmin_hostgroup_map = utils.read_map_file( os.path.join(self.config.map_dir, "siteadmin_hostgroup_map.txt"))
def scan(graph, connectionInfo, logger, thread): """ Get the Firewall Ruleset of the network components stored in the graph. Necessary values in the configuration file of this collector module: - timeout Timeout this collector module shall use (Integer) - zabbixURL URL of the ZabbixServer - zabbixUser Username we want to use to connect to the ZabbixServer - zabbixPassword Password we want to use for the connection - firewallDumpValue Value we request from the ZabbixServer. The value must return a firewall dump in the iptables-save syntax - firewallTypeValue (Optional) We request this value to get the type of the firewall, e.g. iptables :param graph: Data interface object for this collector module :type graph: insalata.model.Graph.Graph :param connectionInfo: Information needed to connect to xen server :type connectionInfo: dict :param logger: The logger this scanner shall use :type logger: logging:Logger :param thread: Thread executing this collector :type thread: insalata.scanner.Worker.Worker """ logger.info("Collecting firewall information using Zabbix Server") zabbixConnection = None timeout = int(connectionInfo['timeout']) name = connectionInfo['name'] try: zabbixConnection = pyzabbix.ZabbixAPI( url=connectionInfo["zabbixURL"], user=connectionInfo["zabbixUser"], password=connectionInfo["zabbixPassword"]) except urllib.error.URLError: logger.error("Can not connect to Zabbix Server {0}.".format( connectionInfo["zabbixURL"])) return except pyzabbix.api.ZabbixAPIException: logger.error( "Username or password invalid for Zabbix Server {0}. User: {1}, Password: {2}." .format(connectionInfo["zabbixURL"], connectionInfo["zabbixUser"], connectionInfo["zabbixPassword"])) return for host in graph.getAllNeighbors(Host): try: param = {"filter": {"host": host.getID()}} answer = zabbixConnection.do_request("host.get", param) if len(answer["result"]) == 0: continue logger.debug( "Collecting firewall information using Zabbix for host {0}.". format(host.getID())) param = { "hostids": answer["result"][0]["hostid"], "search": { "key_": connectionInfo["firewallDumpValue"] } } answer = zabbixConnection.do_request("item.get", param) if len(answer["result"]) == 0: logger.error( "Agent on host {0} does not support the key {1}. Zabbix Server: {2}" .format(host.getID(), connectionInfo["firewallDumpValue"], connectionInfo["zabbixURL"])) continue firewallDump = answer["result"][0]["lastvalue"] #Test if firewall type is known if "firewallTypeValue" in connectionInfo: param = { "hostids": answer["result"][0]["hostid"], "search": { "key_": connectionInfo["firewallTypeValue"] } } answer = zabbixConnection.do_request("item.get", param) if len(answer["result"]) == 0: #Not supported logger.debug( "Key {0} not supported by agent of host {1}.".format( connectionInfo["firewallTypeValue"], host.getID())) continue firewalType = answer["result"][0]["lastvalue"] raw = graph.getOrCreateFirewallRaw(name, timeout, host, firewalType, firewallDump) host.setFirewallRaw(raw) filename = ".firewallDump" + "".join( random.choice(string.ascii_uppercase + string.digits) for _ in range(20)) + ".tmp" with open(filename, 'r+') as dumpFile: dumpFile.write(firewallDump) for chain in getChains(firewallDump): p = subprocess.call(["/etc/insalata/template/fffuu/fffuu", ""], shell=True, stdout=subprocess.PIPE) out, _ = p.communicate() for rule in splitOutput(out): inInterface = outInterface = None if "inInterface" in rule: interfaces = [ i for i in host.getAllNeighbors(Interface) if i.getID() == rule["inInterface"] ] if len(interfaces) > 0: inInterface = interfaces[0] else: logger.error( "Could not find the correct inInterface({0}) for a firewall rule on host {1}." .format(rule["inInterface"], host.getID())) continue if "outInterface" in rule: interfaces = [ i for i in host.getAllNeighbors(Interface) if i.getID() == rule["outInterface"] ] if len(interfaces) > 0: inInterface = interfaces[0] else: logger.error( "Could not find the correct outInterface({0}) for a firewall rule on host {1}." .format(rule["outInterface"], host.getID())) continue rule = graph.getOrCreateFirewallRule( name, timeout, host, chain, rule["action"], rule["protocol"], rule["source"], rule["destination"], rule["srcports"], rule["destPorts"], inInterface, outInterface) host.addFirewallRule(rule) os.remove(filename) except: logger.error( "Error while gathering values from Zabbix Server {0}.".format( connectionInfo["zabbixURL"]))
# zapis polozky - prefix "zbx-" je kvuli nazvu proxy v Zabbixu proxies_with_hosts["zbx-" + item["networks_id"]][item["name"]] = { "id": item["id"], "date_mod": item["date_mod"], } # Ukonceni pripojeni do GLPI connector.kill_session() ################################################################################################################## # Zabbix import ######################### ################################################################################################################## # Vytvoreni API zapi = pyzabbix.ZabbixAPI(ZABBIX_SERVER) zapi.session.verify = ZABBIX_CERT # Prihlaseni k API zapi.login(ZABBIX_USER, ZABBIX_PASSWORD) logger.debug("Prace se Zabbixem") # ziskani dvojic "nazev:ID": proxy, skupiny, sablony all_zabbix_proxies = pyzabbix.get_zabbix_items("proxy", zapi) all_zabbix_groups = pyzabbix.get_zabbix_items("hostgroup", zapi) all_zabbix_templates = pyzabbix.get_zabbix_items("template", zapi) # Citace created_hosts_counter = 0 deleted_hosts_counter = 0
with open(str_opt_path, 'r+t') as rd_js: dct_opt = m_json.load(rd_js) ####################################### def cdp_icon_get(i_cdp: str) -> str: for tpl_kv in dict(dct_opt['node_icon_off']).items(): if m_re.fullmatch(tpl_kv[0], i_cdp) is not None: return str(tpl_kv[1]) return str(dct_opt['node_icon_def']) obj_zbx = m_zbx.ZabbixAPI(dct_opt["zbx_host"]) obj_zbx.login(dct_opt['zbx_login'], dct_opt['zbx_password']) str_groupid_l = [] for str_name in dct_opt["host_group_l"]: for obj_hg in obj_zbx.hostgroup.get(output=["name"], search={"name": str_name}): if obj_hg["name"] == str_name: str_groupid_l += [obj_hg["groupid"]] dct_hid: dict = {} dct_hname: dict = {} str_hunk_s: set = set() tpl_hcnn_s: set = set() dct_hcnn_d: dict = dict()
setup_api_logging(app) jinja2 = Environment( loader=FileSystemLoader(basedir + '/zpark/templates'), autoescape=select_autoescape(['html', 'xml']), trim_blocks=True, lstrip_blocks=True ) try: spark_api = CiscoSparkAPI(access_token=app.config['SPARK_ACCESS_TOKEN']) except ciscosparkapiException as e: app.logger.critical('Unable to authenticate to the Spark API.' ' Please configure/validate SPARK_ACCESS_TOKEN in app.cfg') app.logger.critical('Spark communication is now disabled') spark_api = None zabbix_api = pyzabbix.ZabbixAPI(app.config['ZABBIX_SERVER_URL']) zabbix_api.session.verify = app.config['ZABBIX_TLS_CERT_VERIFY'] try: zabbix_api.login(app.config['ZABBIX_USERNAME'], app.config['ZABBIX_PASSWORD']) except pyzabbix.ZabbixAPIException as e: app.logger.critical('Unable to authenticate to the Zabbix API at {}: {}' .format(app.config['ZABBIX_SERVER_URL'], e)) # API v1 from zpark.v1 import api_v1, api_v1_bp, API_VERSION_V1 app.register_blueprint(api_v1_bp, url_prefix='/api/v{}'.format(API_VERSION_V1))
def _collect_pod(self, conn, cbis_pod_name, cbis_pod_id, cbis_zabbix_url, cbis_zabbix_username, cbis_zabbix_password): self.log.info('connecting to %s (zabbix url : %s)' % (cbis_pod_name, cbis_zabbix_url)) api = pyzabbix.ZabbixAPI(cbis_zabbix_url) api.session.verify = False api.login(user=cbis_zabbix_username, password=cbis_zabbix_password) hosts = api.host.get(output=['name', 'hostid'], search={'name': 'overcloud-'}) host_ids = [] host_data = {} for host in hosts: host_id = host['hostid'] host_ids.append(host_id) host_data[host_id] = host items = api.item.get(hostids=host_ids, monitored=True, filter={'key_': self._item_keys}, output=['name', 'key_', 'value_type', 'hostid', 'units']) items_id_from_type = collections.defaultdict(list) items_data = {} for item in items: item_id = item['itemid'] items_id_from_type[item['value_type']].append(item_id) items_data[item_id] = item item['hostname'] = host_data[item['hostid']]['name'] # Possible values: # 0 - numeric float; # 1 - character; # 2 - log; # 3 - numeric unsigned; # 4 - text. cbis_zabbix_last_sync_time = self._from_date time_till = cbis_zabbix_last_sync_time + timedelta(minutes=self._period_data) now = self._to_date has_some_collected = False while cbis_zabbix_last_sync_time <= now and time_till <= now: has_some_collected = True history_objects = [] for item_type in items_id_from_type: self.log.info('Getting (%s) history.get from %s to %s for item_type %s' % ( cbis_pod_name, cbis_zabbix_last_sync_time.strftime('%Y-%m-%d %H:%M:%S'), time_till.strftime('%Y-%m-%d %H:%M:%S'), item_type)) for items_id_by_chunk in util.chunks(items_id_from_type[item_type], 100): for i in range(4): try: history_objects.extend(api.history.get(itemids=items_id_by_chunk, history=item_type, time_from=int(cbis_zabbix_last_sync_time.strftime('%s')), time_till=int(time_till.strftime('%s')), sortfield=['itemid', 'clock'])) break except Exception as e: self.log.exception('error getting history (%s), retrying for %s [%s]' % (cbis_pod_name, i, e)) #update begin time cbis_zabbix_last_sync_time = time_till time_till = cbis_zabbix_last_sync_time + timedelta(minutes=self._period_data) # raw records row_records = [] # add time_till as the sync point of time all_clock_timestamp = [cbis_zabbix_last_sync_time.strftime('%s')] for history in history_objects: item_id = history['itemid'] item = items_data[item_id] value = history['value'] clock = history['clock'] all_clock_timestamp.append(float(history['clock'])) item_value_type = item['value_type'] row_records.append({'cbis_pod_id': cbis_pod_id, 'hostname': item['hostname'], 'item_key': item['key_'], 'item_value': value, 'item_unit': item['units'], 'clock': clock}) if len(row_records) > 10000: self._save_raw(conn, row_records) row_records = [] if len(row_records) > 0: self._save_raw(conn, row_records) row_records = [] if not has_some_collected: self.log.info('Nothing to collect since current period not full period yet. ')
requests.packages.urllib3.disable_warnings(InsecureRequestWarning) zuser = (args.username or os.getenv('ZABBIX_USER')) zpass = (args.password or os.getenv('ZABBIX_PASS')) apihost = (args.apihost or os.getenv('ZABBIX_API')) if not zuser or not zpass: print "You must specify zabbix apihost, username, password via cli or ENV" sys.exit(1) if not args.action: print "You need to specify action" sys.exit(1) zapi = pyzabbix.ZabbixAPI(apihost) zapi.session.auth = (zuser, zpass) zapi.session.verify = False zapi.login(zuser, zpass) if args.verbose: print "Connected to Zabbix API Version %s" % zapi.api_version() # Default is to return 1 (available), even if zabbix proxy does not exist for the specified host. proxy_dep_alive = 1 proxyhost = zapi.host.get(filter={"host": args.hostname}, output="extend", limit=1) proxyhost_id = proxyhost[0]['proxy_hostid'] proxyhost_hostid = proxyhost[0]['hostid']
def estimate_database_size(args, logger): if not args.url.startswith('http'): newurl = '{}{}{}'.format(args.prefix, args.url, args.suffix) logger.warning('URL (--url) does not start from "http".') logger.warning('Using "{}" for actual URL.'.format(newurl)) args.url = newurl logger.debug('Connecting to "{}" with user "{}"'.format( args.url, args.username)) zapi = pyzabbix.ZabbixAPI(args.url) logger.debug('Zabbix Server version: {}'.format(zapi.api_version())) if not args.password: args.password = getpass.getpass('Password for {}: '.format( args.username)) zapi.login(args.username, args.password) #if args.template: # logger.debug('Look for template instead of host') if args.hosts: hosts = [] for host in args.hosts: result = zapi.host.get(output='extend', filter={'host': host}) if len(result) == 0: logger.error('No hostid for "{}"'.format(result)) continue if len(result) > 1: logger.warning('More than one hostid for "{}" ({}).'.format( host, result)) return hosts.extend(result) else: hosts = zapi.host.get(output='extend') logger.debug('hosts: {}'.format(hosts)) total_items = 0 total_bytes = 0 max_host_len = reduce(lambda x, host: max(x, len(host['host'])), hosts, 0) for host in hosts: items = zapi.item.get(filter={'hostid': host['hostid']}, output='extend', templated=False) logger.debug('host: {} ({} items)'.format(host['host'], len(items))) total_items += len(items) subtotal_bytes = 0 for item in items: logger.debug('item: {}'.format(item)) refresh_rate = int(item['delay']) history = int(item['history']) trends = int(item['trends']) subtotal_bytes += ((history * (24.0 * 3600)) / refresh_rate) * 50 subtotal_bytes += (24.0 * trends) * 128 host_tmpl = '{:<' + str(max_host_len) + '}' logger.info((host_tmpl + '(id: {:3}): {:.2f} MB ({} items)').format( host['host'], host['hostid'], subtotal_bytes / 1024 / 1024, len(items))) total_bytes += subtotal_bytes if total_bytes > 1024 * 1024 * 1024: total_str = '{:.3f} GB'.format(total_bytes / (1024 * 1024 * 1024)) elif total_bytes > 1024 * 1024: total_str = '{:.3f} MB'.format(total_bytes / (1024 * 1024)) elif total_bytes > 1024: total_str = '{:.3f} KB'.format(total_bytes / 1024) else: total_str = '{} B'.format(total_bytes) print('Total: {} (Estimated Max. Not includes Event data!)'.format( total_str))
def login(user, server, password): """Login to zabbix server""" return pyzabbix.ZabbixAPI(user=user, url=server, password=password)
subparser.add_argument("user") subparser = subparsers.add_parser("remote-shell") subparser.add_argument("remote_host") subparser.add_argument("remote_port") args = parser.parse_args() if args.command == "remote-shell": evil_command = COMMANDS["remote-shell"].format(**vars(args)) if args.command == "escalation": evil_command = COMMANDS["escalation"].format(**vars(args)) else: evil_command = COMMANDS[args.command] zapi = pyzabbix.ZabbixAPI(args.url) zapi.login(args.username, args.password) version_string = zapi.api_version() version = tuple(map(int, version_string.split("."))) print("Connected to Zabbix API Version {}".format(version_string)) try: hostid = zapi.host.get(filter={"host": "Host"})[0]["hostid"] print("Creating item: Example item") zapi.item.create(name="Example item", key_="zabbix[boottime]", hostid=hostid, type=5, interfaceid=1,
def main(): parser = argparse.ArgumentParser( description=('Start maintenance right now')) parser.add_argument('hostname', action='store') parser.add_argument( '-d', '--delete-existing', action='store_true', help=('Remove an existing maintenance with same name.')) parser.add_argument('--user', action='store', default='admin') parser.add_argument('--password', action='store', help='Specify password if you really want.') parser.add_argument('--name', action='store', default='Shot maintenance', help='Maintanance name') parser.add_argument('--period', action='store', default='1h', help=('How long the maintenance should be.' 'Seconds or something like "2h" / "30m".' 'No complicated values will be accepted :-)')) parser.add_argument('--targets', action='store', nargs='*', help='If empty all hosts will be under maintenance') parser.add_argument('--log', action='store', default='INFO', help=('Set log level. e.g. DEBUG, INFO, WARN')) parser.add_argument('--log-pyzabbix', action='store_true', help=('Show PyZabbix\'s log. Useful if you want' ' to see JSON query that are sent/received.')) args = parser.parse_args() logger = getLogger(__name__) handler = StreamHandler() logger.setLevel(args.log.upper()) handler.setLevel(args.log.upper()) logger.addHandler(handler) if args.log_pyzabbix: pyzabbix.logger.addHandler(handler) pyzabbix.logger.setLevel(args.log.upper()) if args.password: password = args.password else: password = getpass.getpass('Password: '******'s': 1, 'm': 60, 'h': 60 * 60}[m_period.group(2)[0]] period = int(m_period.group(1)) * mul else: logger.error('Failed to parse {}'.format(args.period)) return logger.debug('Connecting to Zabbix host "{}" with user {}'.format( args.hostname, args.user)) zapi = pyzabbix.ZabbixAPI(args.hostname) zapi.login(args.user, password) logger.debug('Zabbix version: {}'.format(zapi.api_version())) filtered = zapi.maintenance.get(filter={'name': args.name}) if filtered: assert len(filtered) == 1 if args.delete_existing: logger.debug( 'Maintenance already exists ({}). Deleting it.'.format( filtered[0])) zapi.maintenance.delete(filtered[0][u'maintenanceid']) else: logger.error('Maintenance already exists ({}).'.format( filtered[0])) return start_time = int(time.time()) end_time = start_time + period start_readable = ( datetime.fromtimestamp(start_time).strftime('%Y-%m-%d %H:%M:%S')) end_readable = ( datetime.fromtimestamp(end_time).strftime('%Y-%m-%d %H:%M:%S')) logger.debug('Creating maintenance "{}", from "{}" till "{}"'.format( args.name, start_readable, end_readable)) hosts = zapi.host.get(output='extend') logger.debug('Creating maintenance for {}'.format( map(lambda x: x[u'name'], hosts))) hostids = map(lambda x: x[u'hostid'], hosts) result = zapi.maintenance.create(name=args.name, active_since=start_time, active_till=end_time, hostids=hostids, timeperiods=[{ 'timeperiod_type': 0, 'start_date': start_time, 'period': period }]) logger.debug('Result: {}'.format(result)) assert len(result[u'maintenanceids']) == 1 logger.info('Created maintenance id: {}'.format( result[u'maintenanceids'][0]))