def addUserToGroup(self, userdn, groupdn): self.printDebug("adding " + userdn + " to " + groupdn) addUsersInGroups(self.conn, [ userdn, ], [ groupdn, ], raise_error=True)
def lambda_handler(event, context): # Getting the sender mail and subject from the SES Event data = json.loads(event['Records'][0]['Sns']['Message']) email = data['mail']['source'] subjectdata = data['mail']['headers'] for keypair in subjectdata: if keypair['name'] == 'Subject': subject = keypair['value'] group = subject.split(",")[1] user = subject.split(",")[0] admin_user = [ "ENTER ALL THE EMAIL ADDRESSES WHICH SHOULD BE ABLE TO SEND THIS EMAIL HERE" ] adgroups = ["ENTER ALL AD GROUPS WHERE PEOPLE CAN BE ASSIGNED TOO HERE"] server = Server('IP OF YOU AD SERVER', use_ssl=True, get_info=ALL) conn = Connection(server, "CN OF YOUR USER WITH 'Account Operator' PERMISSIONS", "PASSWORD", auto_bind=True, auto_referrals=False) print("###SENDER###") print(email) print("###USER###") print(user) print("###GROUP###") print(group) print("###SUBJECTDATA###") print(subjectdata) # If the sender is part of admin_user it looks up the user and group cn if email in admin_user: user_dn = find_user(user, conn, email) group_dn = find_group(group, conn, email) print(user_dn) print(group_dn) addUsersInGroups(conn, user_dn[:-1], group_dn[:-1]) success_template(email) else: send_error_mail("no_permission", email)
def add_member_to_group(self, AD_SERVER, SEARCH_BASE, BIND_USERNAME, BIND_PASSWORD, MEMBER_NAME, GROUP_NAME): tlsconfig = Tls(validate=ssl.CERT_NONE) server = Server(AD_SERVER, port=636, use_ssl=True, tls=tlsconfig, get_info=ALL) # print(AD_SERVER, BIND_USENAME, BIND_PASSWORD, SEARCH_OBJ) try: conn = Connection(server, BIND_USERNAME, BIND_PASSWORD) conn.start_tls() if not conn.bind(): return 'Bind ERROR {}'.format(conn.result) group_dn = self.get_ad_users_group_dn(AD_SERVER, SEARCH_BASE, BIND_USERNAME, BIND_PASSWORD, 'group', GROUP_NAME) user_dn = self.get_ad_users_group_dn(AD_SERVER, SEARCH_BASE, BIND_USERNAME, BIND_PASSWORD, 'person', MEMBER_NAME) rs = addUsersInGroups(conn, user_dn, group_dn) print(rs, group_dn, user_dn) except Exception as e: return 'SEARCH_ERROR : {}'.format(e) conn.unbind() return 'ADD USER : '******' --- to --- > GROUP : ' + group_dn + " Completed"
def add_member_to_group(self, MEMBER_NAME, GROUP_NAME): group_dn = self.__get_ad_users_group_dn('group', GROUP_NAME) user_dn = self.__get_ad_users_group_dn('person', MEMBER_NAME) print(group_dn, user_dn) try: conn = self.BindADServer() conn.start_tls() # if not conn.bind(): # return 'Bind ERROR {}'.format(conn.result) rs = addUsersInGroups(conn, user_dn, group_dn, raise_error=True, fix=False) print(rs, group_dn, user_dn) except Exception as e: return {'description': 'entryAlreadyExists', 'result': str(e)} conn.unbind() if rs: return { 'desctiption': 'success', 'user_dn': user_dn, 'group_dn': group_dn, 'operation': 'add member to group' }
def add_user_and_group_to_ad(): #adding user and group for management zabbix server_name = session['name'] + '.' + session['domain'] connection_user = session['domain'] + '\\' + session['user'] server = Server(server_name, get_info=ALL) connect = Connection(server, user=connection_user, password=session['password'], authentication=NTLM) connect.bind() #Получение полного доменного имени base = server.info.other.get('defaultNamingContext')[0].lower() for s in base.split(','): if s.starts_with('dc'): base_temp.push(s) #Преобразование array в string dbase = ','.join(base_temp) usersDnList = [] groupsDnList = [] #DistinguishedName user_ou = 'OU=Users,' + dbase group_ou = 'OU=Users,' + dbase #Создание и добавление группы в active directory current_group = 'cn=' + session['group'] + ',' + group_ou groupsDnList.append(current_group) connect.add(current_group, 'group') #Создание и добавление пользователя в active directory current_user = '******' + session['admin'] + ',' + user_ou usersDnList.append(current_user) connect.add( current_user, 'User', { 'givenName': session['admin'], 'sn': session['admin'], 'userPrincipalName': session['admin'] + '@' + session['domain'], #[email protected] 'sAMAccountName': session['admin'], #login 'userPassword': session['admin_password'] }) #password #Функция добавляющая списки пользователей в списки групп add_to_ad = addUsersInGroups(connect, usersDnList, groupsDnList) return add_to_ad
async def add_vpn_func(callback_query: types.CallbackQuery): """Добавление в группу с VPN доступом""" conn_3.bind() vpngroup = 'adm-vpn-crt_users_allow-u' conn_3.search(AD_SEARCH_TREE_3, '(&(objectCategory=Group)'f'(cn={vpngroup}))', SUBTREE, attributes=['DistinguishedName']) groupdn = str(conn_3.entries[0].DistinguishedName) groups_list_full = IDs[str(callback_query.from_user.id)][1]['DATA'] \ [IDs[str(callback_query.from_user.id)][1]['NUMBER']].memberOf.values groups_list = [] for group in groups_list_full: groups_list.append(group.rsplit(',', -1)[0][3:]) if vpngroup not in groups_list: try: addUsersInGroups(conn_3, IDs[str(callback_query.from_user.id)][1]['USERDN'], groupdn) await bot.answer_callback_query(callback_query.id) await bot.send_message(chat_id=callback_query.from_user.id, text='В группу добавлен') await bot.send_message(chat_id=callback_query.from_user.id, text='Что сделать с пользователем?', reply_markup=actions_keyboard) await BotStates.WAIT_COMMAND.set() conn_3.unbind() except Exception as e: print(e) await bot.answer_callback_query(callback_query.id) await bot.send_message(chat_id=callback_query.from_user.id, text='Добавить в группу не удалось') await bot.send_message(chat_id=callback_query.from_user.id, text='Что сделать с пользователем?', reply_markup=actions_keyboard) await BotStates.WAIT_COMMAND.set() conn_3.unbind() else: await bot.answer_callback_query(callback_query.id) await bot.send_message(chat_id=callback_query.from_user.id, text='Пользователь уже в группе') await bot.send_message(chat_id=callback_query.from_user.id, text='Что сделать с пользователем?', reply_markup=actions_keyboard) await BotStates.WAIT_COMMAND.set() conn_3.unbind()
def add_user(self, name, product="Group"): user_dn = self.FORMAT_USER_DN.format(name) group_dn = f"CN=Genie_{product},DC=devatac,DC=net" with ldap3.Connection( self.server, user=config.LDAP_USER, password=config.LDAP_PASS ) as connection: # perform the Add operation success = connection.add( dn=user_dn, object_class=["top", "person", "organizationalPerson", "user"], attributes={ "sn": name, "givenName": "Account", "mail": f"{name}@devatac.net", "name": f"Account {name}", "userPrincipalName": f"{name}@devatac.net", "sAMAccountName": name, "accountExpires": datetime.datetime(2222, 1, 1), "displayName": f"Account {name}", }, ) if not success: log(log.ERROR, "Cannot add user [%s]", user_dn) log(log.ERROR, "%s", connection.result) return None success = ad_unlock_account(connection, user_dn) if not success: log(log.ERROR, "Cannot unlock [%s]", user_dn) log(log.ERROR, "%s", connection.result) return None success = addUsersInGroups(connection, user_dn, group_dn) if not success: log( log.ERROR, "Cannot add user [%s] into group [%s]", user_dn, group_dn ) log(log.ERROR, "%s", connection.result) return None for user in self.users: if user.dn == user_dn: return user log(log.ERROR, "Non found [%s]", user_dn) return None
async def add_printer_func(message, userdn): """Функция добавления в принтерную группу""" if str(IDs[str(message.chat.id)][1]['DATA'][0].DistinguishedName)[-26:] != 'DC=comf,DC=PICompany,DC=ru': conn.bind() printer = message.text prngroup = 'prn-prn01pik-'+str(printer)+'-pr-g' conn.search(AD_SEARCH_TREE, '(&(objectCategory=Group)'f'(cn={prngroup}))', SUBTREE, attributes=['DistinguishedName']) try: groupdn = str(conn.entries[0].DistinguishedName) except Exception as e: await bot.send_message(chat_id=message.chat.id, text='Принтер не найден') groups_list_full = IDs[str(message.chat.id)][1]['DATA'] \ [IDs[str(message.chat.id)][1]['NUMBER']].memberOf.values groups_list = [] for group in groups_list_full: groups_list.append(group.rsplit(',', -1)[0][3:]) if prngroup not in groups_list: try: addUsersInGroups(conn, userdn, groupdn) await bot.send_message(chat_id=message.chat.id, text='В группу добавлен') await bot.send_message(chat_id=message.chat.id, text='Что сделать с пользователем?', reply_markup=actions_keyboard) await BotStates.WAIT_COMMAND.set() conn.unbind() except Exception as e: await bot.send_message(chat_id=message.chat.id, text='Добавить в группу не удалось') await bot.send_message(chat_id=message.chat.id, text='Что сделать с пользователем?', reply_markup=actions_keyboard) await BotStates.WAIT_COMMAND.set() conn_3.unbind() else: await bot.send_message(chat_id=message.chat.id, text='Пользователь уже в группе') await bot.send_message(chat_id=message.chat.id, text='Что сделать с пользователем?', reply_markup=actions_keyboard) await BotStates.WAIT_COMMAND.set() conn_3.unbind() else: conn_3.bind() printer = message.text prngroup = 'prn-prn01pik-'+str(printer)+'-pr-l' conn_3.search(AD_SEARCH_TREE_3, '(&(objectCategory=Group)'f'(cn={prngroup}))', SUBTREE, attributes=['DistinguishedName']) try: groupdn = str(conn_3.entries[0].DistinguishedName) print(userdn) print(groupdn) except Exception as e: await bot.send_message(chat_id=message.chat.id, text='Принтер не найден') groups_list_full = IDs[str(message.chat.id)][1]['DATA'] \ [IDs[str(message.chat.id)][1]['NUMBER']].memberOf.values groups_list = [] for group in groups_list_full: groups_list.append(group.rsplit(',', -1)[0][3:]) if prngroup not in groups_list: try: addUsersInGroups(conn_3, userdn, groupdn) await bot.send_message(chat_id=message.chat.id, text='В группу добавлен') await bot.send_message(chat_id=message.chat.id, text='Что сделать с пользователем?', reply_markup=actions_keyboard) await BotStates.WAIT_COMMAND.set() conn_3.unbind() except Exception as e: print(e) await bot.send_message(chat_id=message.chat.id, text='Добавить в группу не удалось') await bot.send_message(chat_id=message.chat.id, text='Что сделать с пользователем?', reply_markup=actions_keyboard) await BotStates.WAIT_COMMAND.set() conn_3.unbind() else: await bot.send_message(chat_id=message.chat.id, text='Пользователь уже в группе') await bot.send_message(chat_id=message.chat.id, text='Что сделать с пользователем?', reply_markup=actions_keyboard) await BotStates.WAIT_COMMAND.set() conn_3.unbind()
def add_user_to_group(self, user: User, groupDn: str): userDn = self.get_user_dn(user) print("Adding user {} to group {}".format(userDn, groupDn)) addUsersInGroups(self.conn, userDn, groupDn, raise_error=True)
def add_user_to_group(self, user, group_name, AD_OU): rndUser = f"CN={user},{AD_OU}" rndGroup = f"CN={group_name},{AD_OU}" addUsersInGroups(self.conn, rndUser, rndGroup)
conn.bind() #must be TRUE if OK conn.add(usersOU, 'organizationalUnit') # add test-ou for users conn.add(groupsOU, 'organizationalUnit') # add test-ou for groups # generate groups data = Text('en') for _ in range(0,10): currentGroup = 'cn='+data.word()+',ou=test-groups,dc=stand,dc=lsd' conn.add(currentGroup, 'group') groupsDnList.append(currentGroup) # add gnerated group to global list for _ in range(0,10): address_country = address.country() # generate OU name conn.add('ou='+address_country+',ou=test-ou,dc=stand,dc=lsd', 'organizationalUnit') #create OU for _ in range (0,10): name = person.name(gender='male') surname = person.surname(gender='male') currentUser = '******'+name+'.'+surname+','+'ou='+address_country+',ou=test-ou,dc=stand,dc=lsd' usersDnList.append(currentUser) # add generated user in global list conn.add(currentUser, 'User', # add user in OU {'givenName': name, 'sn': surname, 'departmentNumber': 'DEV', 'telephoneNumber': 1111}) for _ in range(0,300): rndUser = random.choice(usersDnList) # random user from list rndGroup = random.choice(groupsDnList) # random group from list addUsersInGroups(conn, rndUser, rndGroup) # add user to group