Newer
Older
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
from ldap3 import Server,Connection,HASHED_MD5,MODIFY_REPLACE
from ldap3.utils.hashed import hashed
from re import match
class ldap_control:
def __init__(self,LDAP_CONFIG):
"""
LDAP_CONFIG ={ "port" : "389",
"host":"example.com",
"admin_dn" :"cn=admin,dc=example,dc=com",
"admin_passwd" : "tttttttt",
"user_dn" : "dc=example,dc=com"}
"""
self.user_dn,self.admin_dn,self.admin_passwd,self.host,self.port = LDAP_CONFIG["user_dn"],LDAP_CONFIG["admin_dn"],LDAP_CONFIG["admin_passwd"],LDAP_CONFIG["host"],LDAP_CONFIG["port"]
self.s = Server(host = self.host,port = self.port)
self.c = Connection(self.s,user = self.admin_dn,password = self.admin_passwd,auto_bind=True)
def result(self):
print(self.c.result)
def chech_email_or_name(self,str):
"""
判断 输入为用户名还是邮箱
:param str: 用户输入
:return: ldap 查询用数据
"""
if '@' in str :
result = f'mail={str}'
else:
result = f'cn={str}'
return result
def check_in(self,user_input):
input = self.chech_email_or_name(user_input)
self.c.search(self.user_dn,f'({input})')
print(self.c.entries)
if (self.c.entries ==[]):
return 0
else:
return 1
def add_user(self,username,email,description,passwd):
"""
:param username:
:param email:
:param description:
:return: 1,成功 0,失败
"""
att ={"cn":f'{username}',
"Mail":f"{email}",
"sn":f"{description}",
"userPassword":""
}
#try:
self.c.add(dn = f'cn={username},{self.user_dn}', object_class=['inetOrgPerson', 'top'], attributes=att)
self.reset_passwd(email,passwd)
print(self.c.result)
return 1
#except:
#return 0
def reset_passwd(self,user__input,newpasswd):
"""
通过用户名 (CN) 或邮箱(mail)重置密码
:param username:
:param newpasswd:
:return: 1 成功 0 失败
"""
input = self.chech_email_or_name(user__input)
user_dn = f'cn={user__input},{self.user_dn}'
hashed_password = hashed(HASHED_MD5, newpasswd)
changes = {
'userPassword': [(MODIFY_REPLACE, [hashed_password])]
}
#try:
self.c.modify(user_dn, changes=changes)
print(self.c.result)
return 1
#except:
#return 0
class User :
def __init__(self,user_info):
self.name = user_info['user_name']
self.mail = user_info['email']
#if self.check_user_input_mail(self.mail) == 0:
#return(0)
#if self.check_user_input_name(self.name) == 0:
#return(0)
self.passwd = user_info['password']
self.description = user_info['description']
def check_user_input_name(string):
if string.isalnum() :
return 1
else:
return 0
def check_user_input_mail(string):
if match(r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$", string):
return 1
else :
return 0
def creat_ldap_account(self,ldap_control):
ldap_control.add_user(self.name,self.mail,self.description,self.passwd)