Manipulating Active Directory Objects¶
This page contains detailed information about how to manipulate various types of Active Directory objects. Keep in mind that all objects subclass ADObject.
ADBase¶
Base class that is utilized by all objects within package to help store defaults. (search, query, all AD objects)
ADObject¶
- class pyad.adobject.ADObject(distinguished_name=None, adsi_ldap_com_object=None, options={})[source]¶
Bases:
pyad.adbase.ADBase
Python object that represents any active directory object.
- add_to_group(group)[source]¶
Adds current object to the specified group. group expects an ADGroup object.
- property adsPath¶
ADsPath of Active Directory object (such as ‘LDAP://cn=me,…,dc=com’
- append_to_attribute(attribute, valuesToAppend, flush: bool = True)[source]¶
Appends values in list valuesToAppend to the specified multi-valued attribute. valuesToAppend can contain a single value or a list of multiple values.
- clear_attribute(attribute, flush: bool = True)[source]¶
Clears (removes) the specified LDAP attribute from the object. Identical to setting the attribute to None or [].
- property dn¶
Distinguished Name (DN) of the object
- dump_to_xml(whitelist_attributes: list = [], blacklist_attributes: list = [])[source]¶
dump_to_xml Dumps object and all human-readable attributes to an xml document which is returned as a string.
- Parameters
whitelist_attributes (list, optional) – Returns only these attributes in the XML document, defaults to []
blacklist_attributes (list, optional) – Returns all available attributes except these, defaults to []
- Returns
The XML Document
- Return type
str
- classmethod from_com_object(com_object)[source]¶
Generates ADObject based on an existing ADSI com object
- classmethod from_dn(distinguished_name, options={})[source]¶
Generates ADObject based on distinguished name
- get_allowed_attributes()[source]¶
Returns a list of allowed attributes for the particular object. These attributes may be defined, but are not guaranteed to be.
- get_attribute(attribute, always_return_list=True, source='LDAP')[source]¶
get_attribute Get an attribute from the AD Object that is represented by this class
Note to experienced ADSI users:
- If an attribute is undefined, getAttribute() will return None or [] and will not
choke on the attribute.
- In regards to always_return_list, True has similar behavior to getEx() whereas
False is similar to Get().
- Parameters
attribute (str) – any schema-allowed LDAP attribute (case insensitive). The attribute does not need to be defined.
always_return_list (bool, optional) – if an attribute has a single value, this specifies whether to return only the value or to return a list containing the single value. Similarly, if true, a query on an undefined attribute will return an empty list instead of a None object. If querying an attribute known to only contain at most one element, then it is easier to set to false. Otherwise, if querying a potentially multi-valued attribute, it is safest to leave at default., defaults to True
source (str, optional) – One of [LDAP,GC], defaults to ‘LDAP’
- Raises
InvalidAttribute – The Requested attrubute doesn’t exist or isn’t valid for this object type
- Returns
a string like object or a list of strings
- Return type
AnyStr or List[AnyStr]
- get_domain()¶
Returns the domain to which the object belongs.
- get_last_login() datetime.datetime [source]¶
get_last_login Returns datetime object of when user last login on the connected domain controller.
- Returns
The date and time that the password was last set (default 1970-01-01)
- Return type
datetime
- get_mandatory_attributes()[source]¶
Returns a list of mandatory attributes for the particular object. These attributes are guaranteed to be defined.
- get_memberOfs(recursive: bool = False, scope: str = 'all') List[pyad.adgroup.ADGroup] ¶
Returns a list of groups that the current object is a member of.
- Parameters
recursive (bool, optional) – This determines whether to return groups that the object is nested into indirectly, defaults to False
scope (str ["domain","forest","all"], optional) – Only return group membership within the current domain (queries from domain) (scope=domain), the forest (will only include universal groups, queries from global catalog) (scope=forest), or both (scope=all), defaults to “all”
- Returns
ADGroup
- Return type
List[ADGroup]
- get_optional_attributes()[source]¶
Returns a list of optional attributes for the particular object. These attributes may be defined, but are not guaranteed to be.
- get_uSNChanged() int [source]¶
get_uSNChanged Returns uSNChanged as a single integer from the current domain controller
- Returns
the iSNChanged value
- Return type
int
- get_user_account_control_settings()[source]¶
Returns a dictionary of settings stored within UserAccountControl. Expected keys for the dictionary are the same as keys in the ADS_USER_FLAG dictionary. Further information on these values can be found at http://msdn.microsoft.com/en-us/library/aa772300.aspx.
- property guid¶
Object GUID of the object
- property guid_str¶
Object GUID of the object
- is_member_of(group: pyad.adgroup.ADGroup, recursive=False) bool ¶
Check whether this object is a member of the given group
- Parameters
group (ADGroup) – The group to check if an object is a member of
recursive (bool, optional) – This determines whether to return groups that the object is nested into indirectly, defaults to False
- Returns
True if the object is a member of the group, False otherwise
- Return type
bool
- move(new_ou_object) None [source]¶
move Moves the object to a new organizationalUnit.
new_ou_object expects a ADContainer object where the current object will be moved to.
- Parameters
new_ou_object (ADContainer) – The destination ADContainer to move the object to
- property parent_container¶
Object representing the container in which this object lives
- property parent_container_path¶
Returns the DN of the object’s parent container.
- property prefixed_cn¶
Prefixed CN (such as ‘cn=mycomputer’ or ‘ou=mycontainer’ of the object
- remove_from_attribute(attribute, valuesToRemove, flush: bool = True)[source]¶
Removes any values in list valuesToRemove from the specified multi-valued attribute.
- remove_from_group(group)[source]¶
Removes current object from the specified group. group expects an ADGroup object to which the current object belongs.
- rename(new_name, set_sAMAccountName=True)[source]¶
Renames the current object within its current organizationalUnit. new_name expects the new name of the object (just CN not prefixed CN or distinguishedName).
- set_user_account_control_setting()[source]¶
set_user_account_control_setting Sets a single setting in UserAccountControl.
UserFlag must be a value from ADS_USER_FLAG dictionary keys. More information can be found at http://msdn.microsoft.com/en-us/library/aa772300.aspx. newValue accepts boolean values
- Parameters
userFlag (ADS_USER_FLAG) – the userAccountControl flag to modify on the user.
newValue (bool) – Enable or Disable the flag
- Raises
ValueError – If the provided userFlag is invalid or newValue is not a bool
- property sid¶
Get the SID of the Active Directory object
- property type¶
pyAD object type (user, computer, group, organizationalUnit, domain).
ADUser¶
- class pyad.aduser.ADUser(distinguished_name=None, adsi_ldap_com_object=None, options={})[source]¶
Bases:
pyad.adobject.ADObject
- classmethod create(name, container_object, password=None, upn_suffix=None, enable=True, optional_attributes={})[source]¶
Creates and returns a new active directory user
- force_pwd_change_on_login(flush: bool = True)[source]¶
Forces the user to change their password the next time they login
- get_expiration()[source]¶
Gets the expiration date of the password as a datetime object. The _ldap_adsi_obj.AccountExpirationDate can be inaccurate and return the UNIX Epoch instead of the true expiration date.
- get_max_pwd_age()[source]¶
Returns timespan object representing the max password age on a user’s domain
- get_password_expired() bool [source]¶
Returns a bool representing whether the password has expired. The passwordexpired property will often return True even if not expired.
- get_password_last_set() datetime.datetime [source]¶
Returns datetime object of when user last reset their password.
- set_expiration(dt, flush: bool = True) None [source]¶
Sets the expiration date of the password to the given value
ADComputer¶
- class pyad.adcomputer.ADComputer(distinguished_name=None, adsi_ldap_com_object=None, options={})[source]¶
Bases:
pyad.adobject.ADObject
Python class representing a computer object in Active Directory.
ADGroup¶
- class pyad.adgroup.ADGroup(distinguished_name=None, adsi_ldap_com_object=None, options={})[source]¶
Bases:
pyad.adobject.ADObject
The class representing Active Directory groups and the accessors methods specific to groups.
- add_members(members)[source]¶
Accepts a list of pyAD objects or a single pyAD object and adds as members to the group.
- check_contains_member(check_member: pyad.adobject.ADObject, recursive: bool = False) bool [source]¶
Checks whether the check_member is a member of the group
- Parameters
check_member (ADObject) – The object to check for membership of the current group object
recursive (bool, optional) – Whether to recursively check membership or only check direct members, defaults to False
- Returns
Whether the check_member is a member of the group
- Return type
bool
- classmethod create(name, container_object, security_enabled=True, scope='GLOBAL', optional_attributes={})[source]¶
Creates and returns a new group
- get_members(recursive: bool = False, ignore_groups: bool = False) List[pyad.adobject.ADObject] [source]¶
Returns a list of group members.
- Parameters
recursive (bool, optional) – Whether to recursively traverse through nested groups, defaults to False
ignore_groups (bool, optional) – include groups in the list, defaults to False
- Returns
_description_
- Return type
List[ADObject]
- remove_members(members: pyad.adobject.ADObject) None [source]¶
Accepts a list of pyAD objects or a single pyAD object and removes these as members from the group.
- set_group_scope(new_scope: str) None [source]¶
Sets group scope
- Parameters
new_scope (str ["GLOBAL", "UNIVERSAL", "LOCAL"]) – The new group scope.
- Raises
ValueError – If new_scope is not valid
- set_group_type(new_type: str) None [source]¶
Sets group type
- Parameters
new_type (str ['DISTRIBUTION', 'SECURITY']) – the new group type
- Raises
ValueError – new_type is not a valid group type
- sync_membership(new_population: List[pyad.adobject.ADObject]) None [source]¶
Synchronizes membership of group so that it matches the list of entries in new_population
- Parameters
new_population (List[ADObject]) – The list of entries to match against the group
ADContainer¶
- class pyad.adcontainer.ADContainer(distinguished_name=None, adsi_ldap_com_object=None, options={})[source]¶
Bases:
pyad.adobject.ADObject
- create_computer(name: str, enable: bool = True, optional_attributes: Dict[str, Any] = {}) pyad.adcomputer.ADComputer [source]¶
Create a new computer object in the container
- Parameters
name (str) – The computer name
enable (bool, optional) – Whether the computer should be enabled or disabled, defaults to True
optional_attributes (Dict[str,Any], optional) – Additional attributes to set when creating the object, defaults to {}
- Returns
the created computer object
- Return type
- create_container(name: str, optional_attributes: Dict[str, Any] = {}) pyad.adcontainer.ADContainer [source]¶
Create a new organizational unit in the container
- Parameters
name (str) – The name of the container
optional_attributes (Dict[str,Any], optional) – Additional attributes to set when creating the object, defaults to {}
- Returns
the created container object
- Return type
- create_group(name: str, security_enabled: bool = True, scope: str = 'GLOBAL', optional_attributes: Dict[str, Any] = {}) pyad.adgroup.ADGroup [source]¶
Create a new group object in the container
- Parameters
name (str) – The Group Name
security_enabled (bool, optional) – If this is a security enabled group or a distribution group, defaults to True
scope (str, optional) – The scope of group. Must be one of [GLOBAL, LOCAL, UNIVERSAL]. Defaults to “GLOBAL”
optional_attributes (Dict[str,Any], optional) – Additional attributes to set when creating the object, defaults to {}
- Returns
The created group object
- Return type
- create_user(name: str, password: Optional[str] = None, upn_suffix: Optional[str] = None, enable: bool = True, optional_attributes: dict = {}) pyad.aduser.ADUser [source]¶
Create a new user object in the container.
- Parameters
name (str) – The name of the user
password (str, optional) – The password for the user it is strongly recommended to populate this parameter as the account will be created with password not required which will not get clear within AD leading to a security vulnerability.
upn_suffix (str, optional) – The upn suffix for the user, defaults to default upn suffix for the domain.
enable (bool, optional) – Whether the user should be enabled or disabled, defaults to True
optional_attributes (dict, optional) – List of additional attribute to set, defaults to {}
- Returns
the created user object
- Return type
- get_children(recursive: bool = False, filter: Optional[List[pyad.adobject.ADObject]] = None) list [source]¶
returns a list of child containers with in the current container. Optionally the list can be filtered to specific object classes and search through child containers recursively.
- Parameters
recursive (bool, optional) – include children from sub-containers, defaults to False
filter (List[ADObject], optional) – filter to only specific object classes ie ADUser, defaults to None
- Returns
a list of all child objects
- Return type
list
- get_children_iter(recursive: bool = False, filter: Optional[List[pyad.adobject.ADObject]] = None) pyad.adobject.ADObject [source]¶
Iterate over the children objects in the container.
- Parameters
recursive (bool, optional) – enumerate all containers with in the object, defaults to False
filter (List[ADObject], optional) – filter to only specific object classes ie ADUser, defaults to None
- Yield
_description_
- Return type
_type_
- remove_child(child: pyad.adobject.ADObject) None [source]¶
Removes the child object from the domain
ADQuery¶
- class pyad.ADQuery(options: dict = {})[source]¶
Bases:
pyad.adbase.ADBase
ADQuery provides a search interface for active directory. Once initialized, a query can be executed by calling execute_query(). Once initialized and a query executed, the query object can be handled similarly to a File Handle object.
To limit the result set when calling execute_query(), the base_dn, search_scope, and where_clause can be used.
- base_dn: The base distinguished name to search from. ie “CN=Users,DC=example,DC=com”
will only return users from the CN=Users container. if unspecified, the default domain will be used (“DC=example,DC=com”)
search_scope: The scope of the search. Must be one of “subtree”, “onelevel”, or “base”,
subtree: searches the entire subtree of the base_dn (default)
If you are looking for users with a specific attribute value, using this will return all users with that attribute value that exist under the provided base_dn.
onelevel: searches the immediate children of the base_dn
If you are looking for users with a specific attribute value, using this will return only users with that attribute value that exist directly under the current base_dn.
base: searches only the base_dn
If you are looking for users with a specific attribute value, using this will only return a user if you specify that users distinguished name as the base_dn.
- where_clause: The filter to use when searching. ie “samaccountname=’jdoe’” will only
return distinguished names that have the samaccountname of jdoe. multiple filters can be combined using the AND or OR operator and prefixed with NOT.
For example: “samaccountname=’jdoe’ OR samaccountname=’jsmith’ AND objectClass=’person’” will return results that have the samaccountname of jdoe or jsmith and are a person.
- execute_query(attributes: List[str] = ['distinguishedName'], where_clause: Optional[str] = None, type: str = 'LDAP', base_dn: Optional[str] = None, page_size: int = 1000, search_scope: str = 'subtree', options: dict = {}, ldap_dialect: bool = False) None [source]¶
Query active directory with the given parameters. Once completed the class becomes iterable.
- Parameters
attributes (List[str], optional) – A list of active directory attributes to query for each object in the resultant set, defaults to [“distinguishedName”]
where_clause (str, optional) – Apply a filter when querying Active Directory, defaults to None
type (str ["LDAP" or "GC"], optional) – Whether the search should be a GC or LDAP query, defaults to “LDAP”
base_dn (str, optional) – The search path, defaults to root distinguished name for the domain
page_size (int, optional) – maximum number of results to return, defaults to 1000
search_scope (str ["subtree", "onelevel", "base"], optional) – limit the depth of the search, defaults to “subtree”
ldap_dialect (bool, optional) – use the ldap dialect in the where_clause, defaults to False
- Raises
ValueError – if the search_scope is not one of “subtree”, “onelevel”, or “base”
- get_all_results() List[dict] [source]¶
returns all results of the query
- Raises
noExecutedQuery – If the query has not been executed yet.
- Returns
A list of dictionaries of the requested attributes for the query result.
- Return type
list
- get_results() None [source]¶
Iterator for the results of the query.
- Raises
noExecutedQuery – If the query has not been executed yet.
- Yield
A dictionary of the requested attributes for the query result.
- Return type
Iterator[dict]
- get_single_result() dict [source]¶
get_single_result Gets the next result in the result set.
- Raises
noExecutedQuery – if called before calling execute_query()
- Returns
values for the query result
- Return type
dict
ADDomain¶
- class pyad.ADDomain(distinguished_name=None, adsi_ldap_com_object=None, options={})[source]¶
Bases:
pyad.adcontainer.ADContainer