Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
mldap DocumentationRelease 2
Shaun Meyer
March 02, 2015
Contents
1 mldap2 Package 1
2 uac Module 3
3 adcon Module 7
4 aduser Module 13
5 adgroup Module 15
6 functions Module 17
7 mldap2 Package 19
8 Indices and tables 21
Python Module Index 23
i
ii
CHAPTER 1
mldap2 Package
Mldap2 is a custom AD/LDAP wrapper built using python-ldap. It is used to simplify programmatic access to theusers and groups in a Windows Server 2003 and Windows Server 2008 Active Directory(tm) Domain.
exception __init__.NoSuchObjectBases: exceptions.Exception
Provide a custom exception to call when we have no user to perform an action upon.
__init__.connect(creds)
Args:
creds(dict) having these keys:
• credsfile
• LDAP_USERNAME
• LDAP_PASSWORD
• LDAP_SERVER
• LDAP_BASE
• LDAP_USER_BASE
• LDAP_GROUP_BASE
• LDAP_DOMAIN
Returns A connected adcon.mldap object.
1
mldap Documentation, Release 2
2 Chapter 1. mldap2 Package
CHAPTER 2
uac Module
class uac.uac(value=0, ad_con=None, objectguid=None)Bases: object
An interface to work with userAccountControl flags.
Constants:
ADS_UF_ACCOUNTDISABLE = 2The user account is disabled.
ADS_UF_DONT_EXPIRE_PASSWD = 65536The password for this account will never expire.
ADS_UF_DONT_REQUIRE_PREAUTH = 4194304This account does not require Kerberos pre-authentication for logon.
ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 128The user can send an encrypted password.
ADS_UF_HOMEDIR_REQUIRED = 8The home directory is required.
ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 2048This is a permit to trust account for a system domain that trusts other domains.
ADS_UF_LOCKOUT = 16The account is currently locked out.
ADS_UF_MNS_LOGON_ACCOUNT = 131072This is an MNS logon account.
ADS_UF_NORMAL_ACCOUNT = 512This is a default account type that represents a typical user.
ADS_UF_NOT_DELEGATED = 1048576The security context of the user will not be delegated to a service even if the service account is set astrusted for Kerberos delegation.
ADS_UF_PASSWD_CANT_CHANGE = 64The user cannot change the password. Note You cannot assign the permission settings ofPASSWD_CANT_CHANGE by directly modifying the UserAccountControl attribute. For more informa-tion and a code example that shows how to prevent a user from changing the password, see User CannotChange Password. (http://msdn.microsoft.com/en-us/library/aa746508(v=vs.85).aspx )
ADS_UF_PASSWD_NOTREQD = 32No password is required.
3
http://msdn.microsoft.com/en-us/library/aa746508(v=vs.85).aspx
mldap Documentation, Release 2
ADS_UF_PASSWORD_EXPIRED = 8388608The user password has expired. This flag is created by the system using data from the Pwd-Last-Setattribute and the domain policy.
ADS_UF_SCRIPT = 1The logon script is executed.
ADS_UF_SERVER_TRUST_ACCOUNT = 8192This is a computer account for a system backup domain controller that is a member of this domain.
ADS_UF_SMARTCARD_REQUIRED = 262144The user must log on using a smart card.
ADS_UF_TEMP_DUPLICATE_ACCOUNT = 256This is an account for users whose primary account is in another domain. This account provides useraccess to this domain, but not to any domain that trusts this domain. Also known as a local user account.
ADS_UF_TRUSTED_FOR_DELEGATION = 524288The service account (user or computer account), under which a service runs, is trusted for Kerberos dele-gation. Any such service can impersonate a client requesting the service.
ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 16777216The account is enabled for delegation. This is a security-sensitive setting; accounts with this option enabledshould be strictly controlled. This setting enables a service running under the account to assume a clientidentity and authenticate as that user to other remote servers on the network.
ADS_UF_USE_DES_KEY_ONLY = 2097152Restrict this principal to use only Data Encryption Standard (DES) encryption types for keys.
ADS_UF_WORKSTATION_TRUST_ACCOUNT = 4096This is a computer account for a computer that is a member of this domain.
commit()Commit changes back to the self.objectguid object.
classmethod flags(value)iterate through flags (using dir()) and return a human-legible rendition of account flags.
>>> someUacObject.flags()[’ADS_UF_DONT_EXPIRE_PASSWD’, ’ADS_UF_NORMAL_ACCOUNT’]
instance_flags()
Returns a list of user-readable flags which are set.
>>> someUacObject.flags()[’ADS_UF_DONT_EXPIRE_PASSWD’, ’ADS_UF_NORMAL_ACCOUNT’]
is_set(flag)Check if a specified flag is set.
Returns Boolean
set(flag)Set a UAC flag
Example:
>>> someUacObject.set(uac.ADS_UF_PASSWORD_EXPIRED).commit()
Returns Self so that calls may be chained.
4 Chapter 2. uac Module
mldap Documentation, Release 2
uac_value = 0Default value (0)
unset(flag)Use AND to unset a flag.
>>> someUacObject.set(uac.ADS_UF_PASSWORD_EXPIRED).commit()
Returns Self so that calls may be chained.
5
mldap Documentation, Release 2
6 Chapter 2. uac Module
CHAPTER 3
adcon Module
exception adcon.NoSuchObjectBases: exceptions.Exception
class adcon.mldap(**args)This class is specifically designed to connect to and interact with our Active Directory via ldap.
Named parameters:
• credsfile
• LDAP_USERNAME
• LDAP_PASSWORD
• LDAP_SERVER
• LDAP_BASE
• LDAP_USER_BASE
• LDAP_GROUP_BASE
• LDAP_DOMAIN
add_to_group(sAMAccountName, groupCN)Add a user to a given group
add_to_multivalued(objectguid, attribute, value)
alive()A quick test to verify if a connection is still active.
bgroup(group)
checkidno(idno)Taking an IDNO as only argument, does a search in the employeeNumber LDAP field for this value.
Deprecated since version 2.0: Use getattr_by_filter() instead.
Parameters idno – string containing the users 7-digit ID.NO
Returns sAMAccountName or None
checkuser(samaccountname)Returns a given set of attributes for an SN.
Deprecated since version 2.0: Use getattr() instead.
compare(samaccountname, attr, value)Perform an ldap compare operation on an AD object.
7
mldap Documentation, Release 2
Returns Bool (True for match)
Raises ldap.NO_SUCH_ATTRIBUTE
compare_by_objectguid(objectguid, attr, value)Verify that an AD object has attr set to value (using ldap compare).
Raises: ldap.NO_SUCH_ATTRIBUTE
connect()Try to build a connection.
Note: This shouldn’t (but does) call sys.exit() for ldap.INVALID_CREDENTIALS andldap.SERVER_DOWN exceptions!
create(samaccountname, cn, path, CONSTattributes={})Create a new account with the specified attributes set. All ‘attributes’ are expected to be LDAP attributesexcept for attributes[’password’] which is properly converted for AD’s unicodePwd field.
Parameters
• samaccountname (str) – Username to create
• cn (str) – CN of new account (only the CN=(whatever))
• path (str) – ldap path of OU for new account
• CONSTattributes (dict) – A dict of LDAP attributes for the new account.
create_group(groupname, path, members=[])Create a new group with the specified members.
Parameters
• groupname (str) – Group name to create
• path (str) – base CN of new group
• members (list) – A list of members to pre-populate group.
delete_user(samaccountname)Attempt to delete a given dn by referencing samaccountname.
disconnect()Close the AD/LDAP Connection if it is open.
exists(samaccountname)Check if an account exists based on the presence of a sAMAccountName
Returns bool
get_dn_from_idno(idno)Return a DN for a given ID.NO
get_dn_from_objectguid(objectguid)Return a DN for a given sAMAccountName
get_dn_from_sn(samaccountname)Return a DN for a given sAMAccountName
get_sn_from_dn(DN)Return the sAMAccountName from DN
getattr(samaccountname, attr=’*’)Lookup attributes on a given sAMAccountName. If not specified, return all attributes.
8 Chapter 3. adcon Module
mldap Documentation, Release 2
Parameters attr – String containing one LDAP attribute, a list of LDAP attributes, or a stringcontaining ‘*’ to return all attributes.
Returns Requested attr. If Multiple attributes are requested, returns a a dictionary with attr keys.
Usage:
>>> getattr(sAMAccountName, [attr1, attr2, ...])>>> getattr(samaccountname)
Examples:
>>> mldapObj.getattr("wimpy", "sAMAccountName")’wimpy’
>>> mldapObj.getattr("wimpy")[’mail’]’[email protected]’
>>> mldapObj.getattr("wimpy", [’sAMAccountName’, ’mail’]){’mail’: ’[email protected]’, ’sAMAccountName’: ’wimpy’}
getattr_by_filter(key, value, attr)Performance a search to match an object by attribute value.
Returns The requested value, or None.
Examples:
Get the mail attribute from an AD object identified by sAMAccountName = “wimpy”:
>>> mldapObj.getattr_by_filter(’sAMAccountName’, ’wimpy’, ’mail’)’[email protected]’
Get the objectClass from an AD object identified by sAMAccountName = “wimpy”:
>>> mldapObj.getattr_by_filter(’sAMAccountName’,’wimpy’,’objectClass’)
[’top’, ’person’, ’organizationalPerson’, ’user’]
getattr_old(samaccountname, attr=’*’)Lookup attributes on a given sAMAccountName. If not specified, return all attributes.
Usage: getattr(sAMAccountName, [attr1, attr2, ...]) getattr(samaccountname)
Deprecated since version 2.0: Use getattr() instead.
getattrs_by_filter(key, value, attrlist=None, base=None, pageSize=1000, compare=’=’,addt_filter=’‘)
Search AD by attribute.
Parameters
• attrlist (list) – The attributes desired (None for all)
• compare – Comparison, valid operators: =, >=,
mldap Documentation, Release 2
>>> mldapObj.getattrs_by_filter("sAMAccountName","wimpy")[0][’sAMAccountName’]
’wimpy’
>>> mldapObj.getattrs_by_filter("sAMAccountName","wimpy")[0][’objectClass’]
[’top’, ’person’, ’organizationalPerson’, ’user’]
getgroup(group)Return a group as a adgroup.ADgroup object
getmattr(samaccountname, attr=’*’)Return a multiple, multivalued, attributes from AD.
When working with results from LDAP the scheme is as follows:
C{results[r][n]{attr}[values]}
Where:
• C{r = result number}
• C{n[0] = dn of result}
• C{n[1] = search attributes}
• C{{attr} = dictionary of attribute:[values]}
• C{[values] = list of values (always in list form)}
getuac(samaccountname)Retrieve the userAccountControl field for a given user.
>>> ad.getuac(’shaunt’).flags()[’ADS_UF_NORMAL_ACCOUNT’]
>>> ad.getuac(’shaunt’)
>>> ad.getuac(’wimpy’).set(uac.ADS_UF_PASSWORD_EXPIRED).commit()
Returns a uac.uac object derived from these flags.
getuser(samaccountname_or_dn)Return an object of type ADUser for a given sAMAccountName or DN
getuser_by_filter(attr, value)Retrieve a single user by filter.
Raises Exception if there is more than one match to the filter.
Parameters attr (str) – AD attribute (sAMAccountName, etc)
Returns a list of aduser.ADuser objects or None if there is no match.
Examples:
>>> user = self.getusers_by_filter(attr, value)
10 Chapter 3. adcon Module
mldap Documentation, Release 2
getusers(base=None, objectType=’samaccountname’)Retrieve a list of aduser.ADuser objects (a more Object-Oriented version ofadcon.mldap.listou())
getusers_by_filter(attr, value)Retrieve a list of users by filter.
Parameters attr (str) – AD attribute (sAMAccountName, etc)
Returns a list of aduser.ADuser objects
Examples:
>>> user = self.getusers_by_filter(attr, value)
group(groupCN)Return a list of a given groups’ members
isdisabled(samaccountname)Is a given SN disabled?
isexpired(samaccountname)Is a given sAMAccountName expired?
accountExpires is the number of ticks (100n/s [.0000001s]) since 12:00AM Jan 1, 1601. [#thanksMS]_Additionally, it’s in UTC
If a user object in Active Directory has never had an expiration date, the accountExpires attribute is set toa huge number. The actual value is 2^63 - 1, or 9,223,372,036,854,775,807.
islocked(samaccountname)Is a given account locked?
MSDN has this to say about lockoutTime:
The date and time (UTC) that this account was locked out. This value is stored as a large integer thatrepresents the number of 100-nanosecond intervals since January 1, 1601 (UTC). A value of zero meansthat the account is not currently locked out.
However, further down the MSDN page says:
This attribute value is only reset when the account is logged onto successfully. This means that this valuemay be non zero, yet the account is not locked out. To accurately determine if the account is locked out,you must add the Lockout-Duration to this time and compare the result to the current time, accounting forlocal time zones and daylight savings time.
ismember(samaccountname, group)Check if a given samaccountname is a member of a given group.
listou(base=None, objectType=’sAMAccountName’, pageSize=1000)Return a list all sAMAccountNames in a given OU
move(srcDN, destDN)Move an object from srcDN to destDN.
TodoShould not use print statements here.
move2(samaccountname, destOU)This uses code not available until python-ldap v2.3.2. On RHEL/CentOS 5.8, repositories only havepython-ldap v2.2.0.
11
mldap Documentation, Release 2
Parameters
• samaccountname – The accountname to search and move.
• destOU – the folder to move the samaccountname into.
remove_from_group(sAMAccountName, groupCN)Remove a user from a given group.
remove_from_multivalued(objectguid, attribute, value)
renameUser(old_username, new_username)Rename a given AD object
replace(samaccountname, attribute, value)Replace/Set/Clear the value of a given attribute for the specified user.
replace_by_idno(idno, attribute, value)Replace/Set the value of a given attribute for the specified user (by IDNO).
replace_by_objectguid(objectGUID, attribute, value)Replace/Set the value of a given attribute for the specified user.
resetpw(sAMAccountName, newpass)Wraps around L{self.replace()} to reset a given password.
Note: This attempts the administrative reset using the user this instance used to bind, make sure that ithas the proper AD permissions.
resetpw_by_objectguid(objectGUID, newpass)Perform an administrative password reset. To perform this reset, the account that was used to bind to ldapmust have permissions in AD to reset the password belonging to objectGUID object.
search(first, last)
setuac(samaccountname, new_uac)Set the uac field for a given user.
Parameters new_uac – The decimal representation of the userAccountControl field (actually,any input is ok as long as it converts properly with str() which at this time means string, uacobject, or int. This means ‘512’, 512, uac(512) are all acceptable.
try_member_search(sAMAccountName)
unpack_attributes(result_set)
12 Chapter 3. adcon Module
CHAPTER 4
aduser Module
class aduser.ADuser(username, ad_obj=None, attributes=None)Bases: object
An Active Directory-backed user-representation object.
Parameters
• username – sAMAccountName of the user.
• ad_obj (mldap2) – connected object.
• attributes – Dictionary to initiate with.
Example:
>>> u = ADuser("wimpy", attributes={’mail’: ’[email protected]’,’initial’: ’w’})
Note:__setattr__() is defined, so attribute changes will be made live if an ad_obj is provided.
attr_map = {‘distinguishedName’: ‘distinguishedName’, ‘username’: ‘sAMAccountName’, ‘firstname’: ‘givenName’, ‘lastname’: ‘sn’, ‘initial’: ‘initials’, ‘idno’: ‘employeeNumber’, ‘email’: ‘mail’}attr_map should be moved. It documents a more general mapping to specific AD attributes.
commit()commit back attribute changes to active directory .. note:: deprecated now that __setattr__ has been added.
get_uac()Return the UAC object representing this user.
refresh()Refresh all attributes from Active Directory.
replace(attr, value)Replace a given attribute with a new value and commit any changes immediately.
update_from(other)update user attributes from another user type.
Note: Not implemented.
13
mldap Documentation, Release 2
writable_attributes = [’mail’, ‘givenName’, ‘initials’, ‘sn’, ‘employeeNumber’, ‘userPrincipalName’, ‘sAMAccountName’]writable_attributes are those that are allowed to be written back to AD when using the commit() func-tion.
14 Chapter 4. aduser Module
CHAPTER 5
adgroup Module
class adgroup.ADgroup(groupname, dn, ad_obj=None)Bases: object
A read-only object representation of an Active Directory group. It is intended to be instanciated byadcon.mldap.getgroup().
Implements dict-like semmantics.
Examples:
>>> u = ad.getgroup(’staff’)>>> "wimpy" in uTrue>>> print(u)
15
mldap Documentation, Release 2
16 Chapter 5. adgroup Module
CHAPTER 6
functions Module
This module contains various mldap helper functions
functions.deprecated(message=None)Call this function with an optional message to raise a warning for a depracated function.
functions.epochFromDatetime(dt=datetime.datetime(2015, 3, 2, 1, 27, 21, 51014))Given a datetime object (defaults to now), return the windows datetime field used in the accountExpires field.
The date when the account expires. This value represents the number of 100-nanosecond intervals since January1, 1601 (UTC). A value of 0 or 0x7FFFFFFFFFFFFFFF (9223372036854775807) indicates that the accountnever expires.
functions.epochToDatetime(epoch)Given the windows datetime field used in the accountExpires field, return a datetime object representing it.
The date when the account expires. This value represents the number of 100-nanosecond intervals since January1, 1601 (UTC). A value of 0 or 0x7FFFFFFFFFFFFFFF (9223372036854775807) indicates that the accountnever expires.
functions.flatten(l)Given a list of no elements, return None. given a list of one element, return just the element, given a list of morethan one element, return the list.
functions.now(dt=datetime.datetime(2015, 3, 2, 1, 27, 21, 51003))Return the current datetime.datetime object.
functions.unicodePasswd(str_passwd)Encode password as unicode for AD.
17
mldap Documentation, Release 2
18 Chapter 6. functions Module
CHAPTER 7
mldap2 Package
Mldap2 is a custom AD/LDAP wrapper built using python-ldap. It is used to simplify programmatic access to theusers and groups in a Windows Server 2003 and Windows Server 2008 Active Directory(tm) Domain.
exception __init__.NoSuchObjectBases: exceptions.Exception
Provide a custom exception to call when we have no user to perform an action upon.
__init__.connect(creds)
Args:
creds(dict) having these keys:
• credsfile
• LDAP_USERNAME
• LDAP_PASSWORD
• LDAP_SERVER
• LDAP_BASE
• LDAP_USER_BASE
• LDAP_GROUP_BASE
• LDAP_DOMAIN
Returns A connected adcon.mldap object.
19
mldap Documentation, Release 2
20 Chapter 7. mldap2 Package
CHAPTER 8
Indices and tables
• genindex
• modindex
• search
21
mldap Documentation, Release 2
22 Chapter 8. Indices and tables
Python Module Index
___init__, 19
aadcon, 7adgroup, 15aduser, 13
ffunctions, 17
uuac, 3
23
mldap Documentation, Release 2
24 Python Module Index
Index
Symbols__init__ (module), 1, 19
Aadcon (module), 7add_to_group() (adcon.mldap method), 7add_to_multivalued() (adcon.mldap method), 7ADgroup (class in adgroup), 15adgroup (module), 15ADS_UF_ACCOUNTDISABLE (uac.uac attribute), 3ADS_UF_DONT_EXPIRE_PASSWD (uac.uac at-
tribute), 3ADS_UF_DONT_REQUIRE_PREAUTH (uac.uac at-
tribute), 3ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED
(uac.uac attribute), 3ADS_UF_HOMEDIR_REQUIRED (uac.uac attribute), 3ADS_UF_INTERDOMAIN_TRUST_ACCOUNT
(uac.uac attribute), 3ADS_UF_LOCKOUT (uac.uac attribute), 3ADS_UF_MNS_LOGON_ACCOUNT (uac.uac at-
tribute), 3ADS_UF_NORMAL_ACCOUNT (uac.uac attribute), 3ADS_UF_NOT_DELEGATED (uac.uac attribute), 3ADS_UF_PASSWD_CANT_CHANGE (uac.uac at-
tribute), 3ADS_UF_PASSWD_NOTREQD (uac.uac attribute), 3ADS_UF_PASSWORD_EXPIRED (uac.uac attribute), 3ADS_UF_SCRIPT (uac.uac attribute), 4ADS_UF_SERVER_TRUST_ACCOUNT (uac.uac at-
tribute), 4ADS_UF_SMARTCARD_REQUIRED (uac.uac at-
tribute), 4ADS_UF_TEMP_DUPLICATE_ACCOUNT (uac.uac at-
tribute), 4ADS_UF_TRUSTED_FOR_DELEGATION (uac.uac at-
tribute), 4ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION
(uac.uac attribute), 4ADS_UF_USE_DES_KEY_ONLY (uac.uac attribute), 4
ADS_UF_WORKSTATION_TRUST_ACCOUNT(uac.uac attribute), 4
ADuser (class in aduser), 13aduser (module), 13alive() (adcon.mldap method), 7attr_map (aduser.ADuser attribute), 13
Bbgroup() (adcon.mldap method), 7
Ccheckidno() (adcon.mldap method), 7checkuser() (adcon.mldap method), 7commit() (aduser.ADuser method), 13commit() (uac.uac method), 4compare() (adcon.mldap method), 7compare_by_objectguid() (adcon.mldap method), 8connect() (adcon.mldap method), 8connect() (in module __init__), 1, 19create() (adcon.mldap method), 8create_group() (adcon.mldap method), 8
Ddelete_user() (adcon.mldap method), 8deprecated() (in module functions), 17disconnect() (adcon.mldap method), 8
EepochFromDatetime() (in module functions), 17epochToDatetime() (in module functions), 17exists() (adcon.mldap method), 8
Fflags() (uac.uac class method), 4flatten() (in module functions), 17functions (module), 17
Gget_dn_from_idno() (adcon.mldap method), 8get_dn_from_objectguid() (adcon.mldap method), 8
25
mldap Documentation, Release 2
get_dn_from_sn() (adcon.mldap method), 8get_sn_from_dn() (adcon.mldap method), 8get_uac() (aduser.ADuser method), 13getattr() (adcon.mldap method), 8getattr_by_filter() (adcon.mldap method), 9getattr_old() (adcon.mldap method), 9getattrs_by_filter() (adcon.mldap method), 9getgroup() (adcon.mldap method), 10getmattr() (adcon.mldap method), 10getuac() (adcon.mldap method), 10getuser() (adcon.mldap method), 10getuser_by_filter() (adcon.mldap method), 10getusers() (adcon.mldap method), 10getusers_by_filter() (adcon.mldap method), 11group() (adcon.mldap method), 11
Iinstance_flags() (uac.uac method), 4is_set() (uac.uac method), 4isdisabled() (adcon.mldap method), 11isexpired() (adcon.mldap method), 11islocked() (adcon.mldap method), 11ismember() (adcon.mldap method), 11
Llistou() (adcon.mldap method), 11
Mmldap (class in adcon), 7move() (adcon.mldap method), 11move2() (adcon.mldap method), 11
NNoSuchObject, 1, 7, 19now() (in module functions), 17
Rrefresh() (aduser.ADuser method), 13remove_from_group() (adcon.mldap method), 12remove_from_multivalued() (adcon.mldap method), 12renameUser() (adcon.mldap method), 12replace() (adcon.mldap method), 12replace() (aduser.ADuser method), 13replace_by_idno() (adcon.mldap method), 12replace_by_objectguid() (adcon.mldap method), 12resetpw() (adcon.mldap method), 12resetpw_by_objectguid() (adcon.mldap method), 12
Ssearch() (adcon.mldap method), 12set() (uac.uac method), 4setuac() (adcon.mldap method), 12
Ttry_member_search() (adcon.mldap method), 12
Uuac (class in uac), 3uac (module), 3uac_value (uac.uac attribute), 4unicodePasswd() (in module functions), 17unpack_attributes() (adcon.mldap method), 12unset() (uac.uac method), 5update_from() (aduser.ADuser method), 13
Wwritable_attributes (aduser.ADuser attribute), 13
26 Index
mldap2 Packageuac Moduleadcon Moduleaduser Moduleadgroup Modulefunctions Modulemldap2 PackageIndices and tablesPython Module Index