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 [].

clear_managedby()[source]

Sets object to be managedBy nobody

delete()[source]

Deletes the object from the domain

disable(flush: bool = True) None[source]

Disables the user or computer

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

enable(flush: bool = True)[source]

Enables the user or computer

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

classmethod from_guid(guid, options={})[source]

Generates ADObject based on GUID

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_managedby(user, flush: bool = True)[source]

Sets managedBy on object to the specified user

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).

update_attribute(attribute, newvalue, no_flush: bool = False)[source]

Updates any mutable LDAP attribute for the object. If you are adding or removing values from a multi-valued attribute, see append_to_attribute and remove_from_attribute.

update_attributes(attribute_value_dict, flush: bool = True)[source]

Updates multiple attributes in a single transaction attribute_value_dict should contain a dictionary of values keyed by attribute name

ADUser

class pyad.aduser.ADUser(distinguished_name=None, adsi_ldap_com_object=None, options={})[source]

Bases: pyad.adobject.ADObject

clear_managedby(flush: bool = True) None[source]

Sets object to be managedBy nobody

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

set_managedby(user, flush: bool = True) None[source]

Sets managedBy on object to the specified user

set_password(password, flush=True)[source]

Sets the users password

unlock(flush: bool = True) None[source]

Unlock the user’s account

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.

classmethod create(name, container_object, enable=True, optional_attributes={})[source]

Creates and returns a new computer object.

get_creator()[source]

returns ADUser object of the user who added the computer to the domain. Returns None if user no longer exists.

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_group_scope() str[source]

Returns the group scope GLOBAL, UNIVERSAL, or LOCAL.

get_group_type() str[source]

Returns group type DISTRIBUTION or SECURITY.

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_all_members() None[source]

Removes all members of the group.

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, enable=True, optional_attributes={})[source]

Create a new computer object in the container

create_container(name, optional_attributes={})[source]

Create a new organizational unit in the container

create_group(name, security_enabled=True, scope='GLOBAL', optional_attributes={})[source]

Create a new group object in the container

create_user(name, password=None, upn_suffix=None, enable=True, optional_attributes={})[source]

Create a new user object in the container

get_children(recursive=False, filter=None) list[source]

Iterate over the children objects in the container.

Parameters
  • recursive (bool, optional) – include children from sub-containers, defaults to False

  • filter (object, optional) – filter to only specific object classes ie ADUser, defaults to None

Returns

a list of all child objects

Return type

list

remove_child(child) 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

seek(pos: int) int[source]

Seek to a specific position in the result set.

Parameters

pos (int) – the position to seek to

Raises

ValueError – if the position is out of range

Returns

the current position in the result set

Return type

int

tell() int[source]

Return the current position in the result set.

Returns

the current position in the result set

Return type

int

ADDomain

class pyad.ADDomain(distinguished_name=None, adsi_ldap_com_object=None, options={})[source]

Bases: pyad.adcontainer.ADContainer

get_default_upn()[source]

Returns the default userPrincipalName for the domain.