-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathldapAdGroupUserAdd
89 lines (72 loc) · 2.7 KB
/
ldapAdGroupUserAdd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import ldap3
from ldap3 import Server, Connection
from ldap3.extend.microsoft.addMembersToGroups import ad_add_members_to_groups as addUsersInGroups
import sys
class AdDetails:
ipaddress = "ip-address of AD server"
domain = 'your domain'
searchbase = 'DC=" ", DC=" " '
username = input("Please enter your username: ")
password = input("Please enter your password: ")
adgroup = input("Enter Active directory group: ")
server = Server(AdDetails.ipaddress, get_info=ldap3.ALL)
try:
conn = Connection(server, AdDetails.username, AdDetails.password, auto_bind=True)
print("*" * 30)
print("Ldap connected \n")
except:
print("*" * 30)
print('LDAP Bind Failed: ')
print("\n")
print("Exit...................")
sys.exit(1)
def group():
conn.search(search_base=AdDetails.searchbase, search_filter='(objectclass=group)', attributes=[ldap3.ALL_ATTRIBUTES,
ldap3.ALL_OPERATIONAL_ATTRIBUTES])
for entry in conn.entries:
gname = entry.name
groups = entry.distinguishedName
if AdDetails.adgroup in gname:
return groups
else:
pass
def error():
if group() is None:
print(f"An error occurred. Group {AdDetails.adgroup} does not exist. ")
sys.exit(1)
def user():
error()
conn.search(search_base=AdDetails.searchbase, search_filter='(objectclass=person)',
attributes=[ldap3.ALL_ATTRIBUTES,
ldap3.ALL_OPERATIONAL_ATTRIBUTES])
with open('users') as f:
users_list = f.read().splitlines()
for entry in conn.entries:
result = entry.name
try:
get = entry.memberOf
except:
get = (entry.name, " No group")
pass
for u in users_list:
if u in result:
if group() in get:
print("*" * 80)
print(f"\n{u} is already member of {group()} \n")
print("Skipped nothing to do ")
elif group() not in get:
dname = entry.distinguishedName
print("*" * 80)
print(f"\n{u} not in group adding user to the {group()} \n")
groups_dn = str(group())
members_dn = str(dname)
addUsersInGroups(conn, members_dn, groups_dn, raise_error="failed", fix="user in group")
print(f"{u} have been added to the group ")
print("*" * 80)
print("\n")
if __name__ == '__main__':
AdDetails
group()
user()
print("\n")
print("Exit...................")