-
Notifications
You must be signed in to change notification settings - Fork 1
/
adinterface.py
66 lines (54 loc) · 2.4 KB
/
adinterface.py
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
import ldaplib
class UserNotFoundException(Exception):
pass
class WillNotPerformException(Exception):
pass
class ADInterface(object):
def __init__(self, config):
"""config must be a dictionary of items (use GetConfig)"""
self.config = config
self.connect()
def connect(self):
"""Connect to AD thru LDAP"""
self.l = ldaplib.ldap_connection((self.config['host'], int(self.config['port'])))
x = self.l.bind(self.config['binddn'], self.config['bindpw'])
if x is not None:
print 'bind error:', x.resultcode, 'error:', x.errorMessage
sys.exit(x)
def makepassword(self, pw):
"""Make a unicodePwd String for Windows AD junk."""
unicode1 = unicode("\"" + pw + "\"", "iso-8859-1")
unicode2 = unicode1.encode("utf-16-le")
password_value = unicode2
del pw
return password_value
def modify(self, dn, attr, values, mode='replace'):
"""values must be a []"""
# [[operation,type,[vals]],[operation,type,[vals]]]
# print 'Modify called:',dn,attr,values,mode
x = self.l.modify(dn, [[mode, attr, values]])
if x.errorMessage:
# ['__doc__', '__init__', '__module__', 'app_code', 'args', 'buffer', 'decode', 'decode_sequence', 'encode', 'errorMessage', 'keyvals', 'matcheddn', 'messageid', 'myargs', 'resultcode']
# print 'dn:', dn
print 'Modify Operation failure res:', x.resultcode, 'error:', x.errorMessage
if x.resultcode == 5:
raise WillNotPerformException('result', x.resultcode, 'error:', x.errorMessage)
# print 'buffer:',x.buffer,'decode',x.decode()
# print dir(x)
return True
def findUser(self, name):
userDN = None
x = self.l.search('sAMAccountName=%s' % (name), self.config['searchdn'], attributes=['distinguishedName'])
# print 'num results:',len(x)
if len(x) > 1:
# print 'returned:',x[0].keyvals
userDN = x[0].keyvals['distinguishedName'][0]
return userDN
# Begin API Calls
def changepass(self, user, passwd):
"""call with string, user and passwd """
passwd = self.makepassword(passwd)
user = self.findUser(user)
if not user:
raise UserNotFoundException('Invalid Username, user not found.')
self.modify(user, 'unicodePwd', [passwd])