SHARE
TWEET

Untitled

a guest Feb 22nd, 2019 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import json
  2. import configparser
  3. import difflib
  4. from keystoneauth1 import session
  5. from keystoneauth1.identity import v2
  6. from keystoneauth1.identity import v3
  7. from keystoneclient.v2_0 import client as ksclient_v2
  8. from keystoneclient.v3 import client as ksclient_v3
  9. from ldap3 import Server, Connection, ALL, ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES
  10.  
  11.  
  12.  
  13. def ad_group_persons(server_name, domain_name, user_name, password, group):
  14.     server = Server(server_name, get_info=ALL)
  15.     conn = Connection(server, user=user_name+'@'+domain_name, password=password, auto_bind=True)
  16.     conn.search('dc=sys,dc=local', "(&(objectCategory=Person)(memberOf=CN=%s,OU=Groups,OU=org,DC=sys,DC=local)(!(useraccountcontrol:1.2.840.113556.1.4.803:=2)))"%(group),
  17.                 attributes=[ALL_ATTRIBUTES, ALL_OPERATIONAL_ATTRIBUTES])
  18.     persons = []
  19.     for e in sorted(conn.entries):
  20.         persons.append(e.sAMAccountName[0])
  21.     return persons
  22.  
  23.  
  24. def _get_config_file_creds(infra_name, config='config.cfg'):
  25.     with open(config) as fp:
  26.         config = configparser.ConfigParser()
  27.         config.read_file(fp)
  28.         creds = {}
  29.         for entry in config.items(infra_name):
  30.             creds[entry[0]] = entry[1]
  31.     return creds
  32.  
  33.  
  34. def _do_auth(**creds):
  35.     if int(creds.get('os_identity_api_version')) == 3:
  36.         auth = v3.Password(username=creds.get('os_username'),
  37.                            password=creds.get('os_password'),
  38.                            project_domain_name=creds.get('os_project_domain_name'),
  39.                            user_domain_name=creds.get('os_user_domain_name'),
  40.                            project_name=creds.get('os_project_name'),
  41.                            auth_url=creds.get('os_auth_url'))
  42.     else:
  43.         auth = v2.Password(username=creds.get('os_username'),
  44.                            password=creds.get('os_password'),
  45.                            tenant_name=creds.get('os_tenant_name'),
  46.                            auth_url=creds.get('os_auth_url'))
  47.     sess = session.Session(auth=auth)
  48.     if int(creds.get('os_identity_api_version')) == 3:
  49.         keystone = ksclient_v3.Client(session=sess)
  50.     else:
  51.         keystone = ksclient_v2.Client(session=sess)
  52.     return keystone
  53.  
  54.  
  55. def _check_defir_groups(client, group):
  56.     for tenant in client.tenants.list():
  57.         ig = dict()
  58.         if tenant.name == f'DEFIR_{group}':
  59.             ig['name'] = tenant.name
  60.             ig['status'] = True
  61.             ig['id'] = tenant.id
  62.             ig['users'] = [u.username for u in client.tenants.list_users(tenant.id)]
  63.             break
  64.         else:
  65.             ig['status'] = False
  66.     return ig
  67.  
  68.  
  69. def Diff(old, new):
  70.     diff = (difflib.unified_diff(old, new, fromfile='a', tofile='b'))
  71.     lines = list(diff)[2:]
  72.     d = dict()
  73.     add = [line[1:] for line in lines if line[0] == '+']
  74.     remove = [line[1:] for line in lines if line[0] == '-']
  75.     d['a'] = [a for a in remove if a not in add]
  76.     d['r'] = [r for r in add if r not in remove]
  77.     return d
  78.  
  79.  
  80. CURRENT='current_users.txt'
  81. OLD="old_users.txt"
  82. group = 'TAM-Users'
  83. main_users = ['admin', 'orchestrator', 'openstack-msk']
  84.  
  85. adcreds={'server_name': 'p0029ad-dc01.sys.local',
  86.        'domain_name': 'sys.local',
  87.        'user_name': 'kvmreport',
  88.        'password': '********',
  89.        'group': 'TAM-Users'}
  90.  
  91. cred = _get_config_file_creds('i04')
  92. auth = _do_auth(**cred)
  93.  
  94.  
  95. class T:
  96.     def __init__(self, auth):
  97.         self.auth = auth
  98.         self._data = self.tenant_info()
  99.         self.users = self.all_users()
  100.         self.roles = self.roles_list()
  101.         return
  102.  
  103.     def tenant_info(self):
  104.         users = {}
  105.         _data = {t.name: {'id': t.id, 'users': users} for t in self.auth.tenants.list() }
  106.         for k, v in _data.items():
  107.             v['users'] = {u.username: u.id for u in self.auth.tenants.list_users(v['id'])}
  108.         return _data
  109.  
  110.     def users_in_tenant(self, tenant):
  111.         _users = [user for user in self._data[tenant]['users']]
  112.         return _users
  113.  
  114.     def all_users(self):
  115.         allu = {u.username: u.id for u in self.auth.users.list()}
  116.         return allu
  117.  
  118.     def user_in_groups(self,user):
  119.         user_tenant = {t[0]: t[1]["id"] for t in self._data.items() if user in t[1]['users'].keys()}
  120.         return user_tenant
  121.  
  122.     def check_user(self, user):
  123.         if user in self.users.keys():
  124.             return self.users[user]
  125.  
  126.     def roles_list(self):
  127.         roles = {role.name: role.id for role in self.auth.roles.list()}
  128.         return roles
  129.  
  130.     def check_tenant(self, tenant):
  131.        for t in self._data:
  132.            if t == f'{tenant}':
  133.                check = True
  134.                break
  135.            else:
  136.                check = False
  137.        return check
  138.  
  139. tinf = T(auth)
  140. all_stack_users = tinf.users
  141. ldap_persons = ad_group_persons(**adcreds)
  142. #ldap_persons = ['evgeniy.gaynutdinov', 'nsuvorov', 'aleksandr.pronin', 'ekaterina.zheludkova']
  143. defir_project = _check_defir_groups(auth, adcreds['group'])
  144.  
  145. if defir_project["status"]:
  146.     print(defir_project['name'])
  147.     state = (Diff(ldap_persons, tinf.users_in_tenant(defir_project['name'])))
  148.     for add in state['a']:
  149.         print("Add to project new user ", add)
  150.         if tinf.check_user(add):
  151.             auth.users.update_tenant(tinf.check_user(add),defir_project['id'])
  152.         else:
  153.             auth.users.create(add, tenant_id=defir_project['id'])
  154.     for remove in state['r']:
  155.         print("Remove from project user ", remove)
  156.         if tinf.check_user(remove):
  157.             auth.users.delete(tinf.check_user(remove))
  158. else:
  159.     auth.tenants.create(f'DEFIR_{adcreds["group"]}')
  160.     new_project = _check_defir_groups(auth, adcreds['group'])
  161.     for user in ldap_persons:
  162.         print(user)
  163.         if user in all_stack_users.keys():
  164.             print("change user project")
  165.             auth.users.update_tenant(all_stack_users[user], new_project["id"])
  166.         else:
  167.             print("create new")
  168.             auth.users.create(user, tenant_id=new_project['id'])
  169.  
  170. with open(f'{adcreds["group"]}_access.json') as steps:
  171.     data = json.load(steps)
  172.  
  173. for os in data.items():
  174.     os_setup = os[0]
  175.     projects = os[1]["projects"]
  176.     for user in ldap_persons:
  177.         if type(projects) == list and projects != []:
  178.             p = [f'tenant_{pr}' for pr in projects]
  179.             p.append(f'DEFIR_{adcreds["group"]}')
  180.             state = Diff(p, list(tinf.user_in_groups(user).keys()))
  181.             if state['a'] != []:
  182.                 for pr in state['a']:
  183.                     if tinf.check_tenant(pr):
  184.                         auth.tenants.add_user(tinf._data[pr]['id'], tinf.users[user], tinf.roles['_member_'])
  185.                     else:
  186.                         print("Project failed")
  187.                 for pr in state['r']:
  188.                     if tinf.check_tenant(pr):
  189.                         auth.tenants.remove_user(tinf._data[pr]['id'], tinf.users[user], tinf.roles['_member_'])
  190.                     else:
  191.                         print("Project failed")
  192.  
  193.         if projects == []:
  194.             if tinf.user_in_groups(user) != {defir_project['name']: defir_project['id']}:
  195.                 print("I need delete user from group ", user)
  196.                 for pr in tinf.user_in_groups(user):
  197.                     if pr != defir_project['name']:
  198.                         print("i need delete from project ", pr)
  199.                         auth.tenants.remove_user(tinf._data[pr]['id'], tinf.users[user], tinf.roles['_member_'])
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top