Collection of CheckMK checks (see https://checkmk.com/). All checks and plugins are provided as is. Absolutely no warranty. Send any comments to thl-cmk[at]outlook[dot]com

Skip to content
Snippets Groups Projects
Commit 31e8ab20 authored by thl-cmk's avatar thl-cmk :flag_na:
Browse files

Delete ciscosupport.py

parent 37af5edb
No related branches found
No related tags found
No related merge requests found
#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
#
# 15.04.2017 : Th.L. : Support for Cisco API
#
# https://developer.cisco.com/docs/support-apis/
#
import logging
import os
import time
import random
import sys
import json
import copy
import ciscoapi
# sleep random time
def sleep_random(max_minutes):
# set logg modul name <file>:<module>.<function>
logger = logging.getLogger(__file__ + ':' + __name__ + '.' + sys._getframe().f_code.co_name)
sleep_time = random.randint(1, 60 * max_minutes)
logger.info('%d seconds' % sleep_time)
time.sleep(sleep_time)
return
def set_logging(loglevel):
numeric_level = getattr(logging, loglevel.upper(), None)
if not isinstance(numeric_level, int):
# set default loglevel if loglevel not valid
logging.basicConfig(level=logging.WARNING, format='%(asctime)s %(levelname)s %(name)s %(message)s')
logging.getLogger().setLevel(logging.WARNING)
else:
logging.basicConfig(level=numeric_level, format='%(asctime)s %(levelname)s %(name)s %(message)s')
logging.getLogger().setLevel(numeric_level)
return
# read list of files from dir (eq. (P)IDs or SERIALs) (don't change to uppercase)
# **kwargs: refresh_time:int in days
def get_ids_from_dir(dir, **kwargs):
# set logg modul name <file>:<module>.<function>
logger = logging.getLogger(__file__ + ':' + __name__ + '.' + sys._getframe().f_code.co_name)
refresh_time = int(kwargs.get('refresh_time', 0)) * 86400
starttime = int(time.time())
ids = []
for (dirpath, dirnames, filenames) in os.walk(dir):
for id in filenames:
modifytime = int(os.path.getmtime(dirpath + '/' + id))
if (starttime - modifytime) > refresh_time:
ids.append(str(id).replace('_', '/'))
# do not read subdirs
break
# insert cleanup here (filter unwanted names, chars, etc...)
return ids
# read list of sub directories from directory (PIDs) (don't anything)
def get_subdirs_from_dir(base_dir):
# set logg modul name <file>:<module>.<function>
logger = logging.getLogger(__file__ + ':' + __name__ + '.' + sys._getframe().f_code.co_name)
sub_dirs = []
for (dirpath, sub_dirs, filenames) in os.walk(base_dir):
break
# insert cleanup here (filter unwanted names, chars, etc...)
return sub_dirs
# read list of IOS/IOSXE Versions from directory (don't change to uppercase)
def get_version_from_dir(dir):
# set logg modul name <file>:<module>.<function>
logger = logging.getLogger(__file__ + ':' + __name__ + '.' + sys._getframe().f_code.co_name)
versions = []
for (dirpath, dirnames, filenames) in os.walk(dir):
for id in filenames:
versions.append(str(id))
# do not read subdirs
break
# insert cleanup here (filter unwanted names, chars, etc...)
return versions
# delete (P)IDs or SERIALs files from directory (requests)
def remove_ids_from_dir(ids, dir):
# set logg modul name <file>:<module>.<function>
logger = logging.getLogger(__file__ + ':' + __name__ + '.' + sys._getframe().f_code.co_name)
for id in ids:
try:
os.remove(dir + id.replace('/', '_'))
except OSError:
pass
# remove (P)IDs or SERIALs from list of (P)ID or serials
def remove_ids_from_list(ids, dir):
# set logg modul name <file>:<module>.<function>
logger = logging.getLogger(__file__ + ':' + __name__ + '.' + sys._getframe().f_code.co_name)
knownids = []
for (dirpath, dirnames, filenames) in os.walk(dir):
knownids.extend(filenames)
# do not read subdirs
break
for knownid in knownids:
knownid = knownid.replace('_', '/')
for id in ids:
if knownid == id:
ids.remove(id)
return ids
# returns al list of ids to refresh,
# expects a directory with ids to check, the time interval, a list of IDs to add
# if remove True it will delete the ID files from refresh_dir
def refresh_ids_from_dir(refresh_dir, refresh_time, ids, remove):
# set logg modul name <file>:<module>.<function>
logger = logging.getLogger(__file__ + ':' + __name__ + '.' + sys._getframe().f_code.co_name)
refresh_dir = expand_path(refresh_dir)
# get seconds from # of days (days * 24 * 60 * 60 --> days * 86400)
refresh_time = int(refresh_time) * 86400
starttime = int(time.time())
refresh_ids = get_ids_from_dir(refresh_dir)
if refresh_ids != []:
for id in refresh_ids:
modifytime = int(os.path.getmtime(refresh_dir + id.replace('/', '_')))
if (starttime - modifytime) > refresh_time:
ids.append(id)
if remove:
try:
os.remove(refresh_dir + id.replace('/', '_'))
except OSError:
pass
return ids
# check if dir exists, if not try to create it.
# return True if dir exists or creation was ok.
# return False if dir not exists and creation was not ok
def check_dir_and_create(dir):
# set logg modul name <file>:<module>.<function>
logger = logging.getLogger(__file__ + ':' + __name__ + '.' + sys._getframe().f_code.co_name)
directory = os.path.dirname(dir)
if not os.path.exists(directory):
try:
os.makedirs(directory)
except:
return False
return True
# expand homedir and add '/' if necessary and create directory if it not exists
def expand_path(path):
# set logg modul name <file>:<module>.<function>
logger = logging.getLogger(__file__ + ':' + __name__ + '.' + sys._getframe().f_code.co_name)
homedir = os.path.expanduser('~')
if path.startswith('~'):
path = homedir + path[1:]
if not path.endswith('/'):
path += '/'
if not check_dir_and_create(path):
return ''
return path
# get cisco product series by pid
def get_cisco_product_series_by_pid(pids, access_token):
set_logging('info')
# set logg modul name <file>:<module>.<function>
logger = logging.getLogger(__file__ + ':' + __name__ + '.' + sys._getframe().f_code.co_name)
conf_file = '~/etc/ciscoapi/ciscoapi.json'
conf_file = os.path.expanduser(conf_file)
productseriesfile = '~/var/ciscoapi/productinfo'
product_series = {}
if os.path.isfile(conf_file):
with open(conf_file) as f:
try:
config = json.load(f)
productseriesfile = config['productinfo'].get('productseriesfile', productseriesfile)
except ValueError as e:
logging.warning(f'snmp_cisco_eox:status:JSON load error: {e}')
productseriesfile = expand_path(productseriesfile) + 'productseries.json'
if os.path.isfile(productseriesfile):
with open(productseriesfile) as f:
product_series = json.load(f)
requestpids = copy.deepcopy(pids)
if product_series != {}:
keys = product_series.keys()
for pid in requestpids:
if pid in keys:
requestpids.remove(pid)
if requestpids != []:
product_infos = ciscoapi.get_product_mdf_information_by_pid(pids, access_token)
for entry in product_infos:
product_series.update({entry.get('product_id'): entry.get('product_series')})
with open(productseriesfile, 'w') as f:
json.dump(product_series, f)
return_product_series ={}
for pid in pids:
return_product_series.update({pid: product_series.get(pid, 'not found')})
return return_product_series
# remove empty directories
def remove_empty_sub_dirs(base_dir):
# set logg modul name <file>:<module>.<function>
logger = logging.getLogger(__file__ + ':' + __name__ + '.' + sys._getframe().f_code.co_name)
subdirs = get_subdirs_from_dir(base_dir)
for subdir in subdirs:
try:
os.rmdir(base_dir + subdir)
except OSError as e:
logger.debug('can not delete: %s, Error:%s' % (base_dir + subdir, e))
pass
# move contents of source_dir to destination_dir
# only one level deep, lave source_dir
def move_dir(source_dir, destination_dir, **kwargs):
refresh_time = int(kwargs.get('refresh_time', 0)) * 86400
starttime = int(time.time())
sub_dirs = get_subdirs_from_dir(source_dir)
for sub_dir in sub_dirs:
files = get_ids_from_dir(source_dir + sub_dir)
if len(files) > 0:
source_path = expand_path(source_dir + sub_dir)
destination_path = expand_path(destination_dir + sub_dir)
for file in files:
source_file = source_path + file
destination_file = destination_path + file
modifytime = int(os.path.getmtime(source_file))
if (starttime - modifytime) > refresh_time:
try:
os.rename(source_file, destination_file) # rename (move) contents of not_found to request
except OSError as e:
logging.warning('ciscoapisupport:move_dir:error:%s, source: %s, destionation: %s' % (e, source_file, destination_file))
remove_empty_sub_dirs(source_dir)
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment