From 4a788fc13376d67a7413780da66484bd75c7cd91 Mon Sep 17 00:00:00 2001 From: Ricardo Silva <Ricardo.SILVA@ext.ec.europa.eu> Date: Wed, 3 Aug 2022 16:37:04 +0200 Subject: [PATCH] added script to create the sid groups lk:31512104363085 --- bin/sid_groups.py | 215 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100755 bin/sid_groups.py diff --git a/bin/sid_groups.py b/bin/sid_groups.py new file mode 100755 index 0000000..3537759 --- /dev/null +++ b/bin/sid_groups.py @@ -0,0 +1,215 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, print_function + +from ldap3 import Server, Connection +import sys +import os +import configparser as ConfigParser +import logging +import argparse +import socket +# import json +from pprint import pformat +import traceback + + +hostname = os.uname()[1] +whoami = sys._getframe().f_code.co_name +script = os.path.basename(__file__) + +for pylib in list(sys.path): + if '/usr/local/lib' in pylib: + sys.path.remove(pylib) + continue + elif '/export/home/snet/.local' in pylib: + sys.path.remove(pylib) + continue + +''' BASE CONFIG ''' +global_iniFile = '/opt/etc/ini/global.ini' +config_global = ConfigParser.RawConfigParser() +config_global.optionxform(str()) +config_global.optionxform = str +config_global.read(global_iniFile) +sys.path.append(config_global.get('APPLICATION', 'PYTHON-LIBRARY')) + +import snet.sloggly +from snet.diego import Diego +from snet.scrat import Scrat + +try: + logger = snet.sloggly.setup_custom_logger(script, logging.INFO) +except Exception as e: + print("\n=======\n") + title = "Something went wrong. Please inform SS team." + msg = "Error initializing the snet logger: " + str(e) + " :: " + traceback.format_exc(5) + print(msg) + whoami = sys._getframe().f_code.co_name + messages = [hostname, script, title, whoami, msg] + traceback.print_exc() + sys.exit(1) + + +def ec_ldap_get(): + + ldap_config_file = config_global.get('INI', 'LDAP') + ldap_config = ConfigParser.RawConfigParser() + ldap_config.optionxform(str()) + ldap_config.optionxform = str + ldap_config.read(ldap_config_file) + + server_name = ldap_config.get('LDAP_EC', 'SERVER_NAME') + server_port = int(ldap_config.get('LDAP_EC', 'SERVER_PORT')) + user = ldap_config.get('LDAP_EC', 'USER') + password = ldap_config.get('LDAP_EC', 'PASSWORD') + basedn = ldap_config.get('LDAP_EC', 'BASE') + + groups = ldap_config.get('LDAP_EC', 'SID_GROUP').split(',') + attributes = ['uid', 'cn'] + + ldap_server = Server(server_name, port=server_port, use_ssl=False) + ldap_con = Connection(ldap_server, user, password, auto_bind=True) + + results = dict() + results['groups'] = dict() + for group in groups: + + filter = "(&(objectclass=*)(cudgroup=%s))" % (group) + ldap_con.search(search_base=basedn, + search_filter=filter, + attributes=attributes) + + results['groups'][group] = dict() + results['groups'][group]['description'] = "nothing" + results['groups'][group]['mapped-ldap-users'] = list() + results['groups'][group]['mapped-ldap-groups'] = list() + + for entry in ldap_con.response: + if attributes[0] in entry['attributes']: + for g in entry['attributes'][attributes[0]]: + results['groups'][group]['mapped-ldap-users'].append(g) + + ldap_con.unbind() + return results + + +def sid_create_user_group(dfqdn, res_rw_user, block_to_update, verify=True, error_stop=False): + + scrat_inst = Scrat(res_rw_user, '', fqdn=dfqdn, version=2, verify=verify) + (scrat_json, scratres) = scrat_inst.scratQuery(block_to_update, Full=True) + + if str(scratres) != '200': + '''Scrat just add the vlan to the trunked list''' + to_print = pformat(block_to_update) + for i in list(range(0, int(round(len(to_print) / 250)) + 1)): + logger.info('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) + + to_print = pformat(block_to_update) + for i in list(range(0, int(round(len(to_print) / 250)) + 1)): + logger.error('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) + # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) + to_print = '%s: %s' % (str(scratres), str(scrat_json)) + for i in list(range(0, int(round(len(to_print) / 250)) + 1)): + logger.error('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) + # print('scrat %s update failed: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) + if error_stop is True: + sys.exit(1) + else: + to_print = pformat(block_to_update) + for i in list(range(0, int(round(len(to_print) / 250)) + 1)): + logger.debug('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) + # print('scrat %s update cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) + +def main(): + + parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, + description='Script to synchronize the CUCM videoconference endpoints' + 'to SID') + + parser.add_argument('-v', '--verbose', action="store_true", default=False, + help="increase output verbosity", dest='verbose') + parser.add_argument('-d', '--debug', action="store_true", default=False, + help="increase output verbosity a lot", dest='debug') + parser.add_argument('--parameter', default=False, + help="the login parameter to debug", dest='param') + parser.add_argument('-e', '--env', default=False, help="Set the wanted env", dest='env', nargs='?', + choices=('dev', 'acc', 'prod')) + parser.add_argument('--dryrun', action="store_true", default=False, + help="print but do nothing", dest='dryrun') + parser.add_argument('--error-stop', action="store_true", default=False, + help="stop at the first errors", dest='error_stop') + parser.add_argument('--rw-user', default=False, required=True, help="Set the user doing the action in SID", dest='rw_user') + + args = parser.parse_args() + + dryrun = args.dryrun + debug = args.debug + logindebug = args.param + res_rw_user = args.rw_user + error_stop = args.error_stop + + if debug: + logger.setLevel(logging.DEBUG) + + verify = True + if args.env is False: + logger.debug('Using the automatic env.') + fqdn = socket.getfqdn() + + elif args.env == 'prod': + fqdn = '10.226.41.24:45789' + verify = False + + elif args.env == 'acc': + fqdn = 'vworker0-lu.acc.snmc.cec.eu.int' + + elif args.env == 'dev': + fqdn = 'vworker-dev.dev.snmc.cec.eu.int' + + else: + logger.error('should not happen') + sys.exit(1) + + print('Using the SID backend: ' + fqdn) + diego = Diego(fqdn=fqdn, verify=verify) + + snet_results = dict() + snet_results = ec_ldap_get() + + if debug: + logger.debug(pformat(snet_results)) + + context_uid = 666000002 + + (header,sid_groups) = diego.diego_run_dieget_by_name('list_user_groups', {}) + + if debug: + logger.debug(sid_groups) + + for group in snet_results['groups']: + need_to_create = False + block_to_update = { + 'name': group, + 'context': context_uid, + 'type': 'user group', + 'properties': { + } + } + if group not in sid_groups: + need_to_create = True + if debug: + logger.debug("GROUP -> " + group + " is to create: " + str(need_to_create)) + + if not dryrun and need_to_create is True: + sid_create_user_group(fqdn, res_rw_user, block_to_update, verify=verify, error_stop=error_stop) + else: + logger.debug('dryrun') + to_print = pformat(block_to_update) + for i in list(range(0, int(round(len(to_print) / 250)) + 1)): + logger.info('scrat %s cmd: %s' % (str(i), to_print[250 * i:250 * (i + 1)])) + sys.exit(1) + +if __name__ == '__main__': + main() -- GitLab