Python active directory module

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.

ADObject¶

Python object that represents any active directory object.

Adds current object to the specified group. group expects an ADGroup object.

ADsPath of Active Directory object (such as ‘LDAP://cn=me. dc=com‘

Appends values in list valuesToAppend to the specified multi-valued attribute. valuesToAppend can contain a single value or a list of multiple values.

Clears (removes) the specified LDAP attribute from the object. Identical to setting the attribute to None or [].

Sets object to be managedBy nobody

Deletes the object from the domain

Disables the user or computer

Distinguished Name (DN) of the object

Dumps object and all human-readable attributes to an xml document which is returned as a string.

Enables the user or computer

Generates ADObject based on an existing ADSI com object

Generates ADObject based on distinguished name

Generates ADObject based on GUID

Returns a list of allowed attributes for the particular object. These attributes may be defined, but are not guaranteed to be.

Returns the value of any allowable LDAP attribute of the specified object.

attribute – any schema-allowed LDAP attribute (case insensitive). The attribute does not need to be defined. always_return_list – 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.

source – either ‘LDAP’ or ‘GC’

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

Returns the domain to which the object belongs.

Returns a list of mandatory attributes for the particular object. These attributes are guaranteed to be defined.

Get the groups that this object is a member of

Returns a list of optional attributes for the particular object. These attributes may be defined, but are not guaranteed to be.

Returns uSNChanged as a single integer from the current domain controller

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.

Object GUID of the object

Object GUID of the object

Check whether this object is a member of the given group

Moves the object to a new organizationalUnit.

Читайте также:  Пример 1

new_ou_object expects a ADContainer object where the current object will be moved to.

Object representing the container in which this object lives

Returns the DN of the object’s parent container.

Prefixed CN (such as ‘cn=mycomputer’ or ‘ou=mycontainer’ of the object

Removes any values in list valuesToRemove from the specified multi-valued attribute.

Removes current object from the specified group. group expects an ADGroup object to which the current object belongs.

Renames the current object within its current organizationalUnit. new_name expects the new name of the object (just CN not prefixed CN or distinguishedName).

Sets managedBy on object to the specified user

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

Get the SID of the Active Directory object

pyAD object type (user, computer, group, organizationalUnit, domain).

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.

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

ADUser¶

Creates and returns a new active directory user

Forces the user to change their password the next time they login

Returns datetime object of when user last reset their password.

Sets the expiration date of the password to the given value

ADComputer¶

Python class representing a computer object in Active Directory.

Creates and returns a new computer object.

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

ADGroup¶

Accepts a list of pyAD objects or a single pyAD object and adds as members to the group.

Checks whether a pyAD object is a member of the group. check_member expects a pyAD object to be checked. recursive expects True/False which determines whether the group membership will be searched recursively.

Creates and returns a new group

Returns the group scope GLOBAL, UNIVERSAL, or LOCAL.

Returns group type DISTRIBUTION or SECURITY.

Returns a list of group members. recursive — True/False. Determines whether to recursively traverse through nested groups. ignoreGroups — True/False. Determines whether or not to return an ADGroup objects in list or to ignore them.

Removes all members of the group.

Accepts a list of pyAD objects or a single pyAD object and removes these as members from the group.

Sets group scope. new_scope expects GLOBAL, UNIVERSAL, or LOCAL.

Sets group type. new_type expects DISTRIBUTION or SECURITY.

Synchronizes membership of group so that it matches the list of entries in new_population

ADContainer¶

Create a new computer object in the container

Create a new organizational unit in the container

Create a new group object in the container

Create a new user object in the container

Iterate over the children objects in the container.

Rremoves the child object from the domain

ADDomain¶

NOTE: ADDomain subclasses ADContainer.

Returns the default userPrincipalName for the domain.

Источник

Active Directory Basics¶

Pyad is designed to expose the ADSI interface to Microsoft Active Directory in a straight-forward Pythonic manner. The library is designed to run on Windows. This page describes the basics of how to use the library. It does not, however, comprehensively describe the functionality of the library, which is more aptly documented in the next section.

Читайте также:  Python replace several characters

Connecting to Active Directory¶

By default, pyad will connect to the Active Directory domain to which the machine is joined (rootDSE):

from pyad import aduser user = aduser.ADUser.from_cn("myuser") 

However, it is possible to connect to a specific domain controller or to use alternate credentials, by calling pyad.set_defaults() or by passing in connection information in the options dictionary for each object you connect to. Authentication is performed over a secured connection, pyad will not pass credentials over clear text. The following options can be set in the set_defaults call: ldap_server , gc_server , ldap_port , gc_port , username , password , and ssl (True/False). For example, the following code will set the default connection parameters for all objects accessed through pyad:

from pyad import * pyad.set_defaults(ldap_server="dc1.domain.com", username="service_account", password="mypassword") user = pyad.aduser.ADUser.from_cn("myuser") 

It is also possible to pass in options when connecting to a specific object. This will not set the library defaults, but these settings will be used from any objects you derive from it (e.g. if you request group membership of a user) Example:

from pyad import aduser user = aduser.ADUser.from_cn("myuser", options=dict(ldap_server="dc1.domain.com")) 

Basic Object Manipulation¶

There are first order Python classes for different types of objects in Active Directory. For example, ADUser represents user objects and ADGroup represents groups. All objects subclass ADObject. Most methods are defined in ADObject, but subclasses generally provide additional helper methods (e.g. ADUser has set_password and ADGroup has add_member ).

It is possible to connect to an object by distinguished name, CN, UPN, and GUID if you already know the type of object. Examples:

from pyad import aduser user1 = aduser.ADUser.from_dn("cn=myuser, ou=staff, dc=domain, dc=com") user2 = aduser.ADUser.from_cn("myuser") user3 = aduser.ADUser.from_guid("XXX-XXX-XXX") 

It is also possible to use the pyad factory with an arbitrary Active Directory object and to receive an appropriately classed Python object:

from pyad import pyad user = pyad.from_cn("user1") computer = pyad.from_dn("cn=WS1,ou=Workstations,dc=domain,dc=com") group = pyad.from_guid("XXX-XXX-XXX") 

Unlike the ADSI interface, pyad objects are intended to interact with one another. Instead of adding the DN of a user to the members attribute of a group to add the user, you instead add the user object to the group. For instance:

user1 = ADUser.from_cn("myuser1") user2 = ADUser.from_cn("myuser2") group = ADGroup.from_dn("staff") group.add_members([user1, user2]) for user in group.get_members(): print user1.description 

However, it is still possible to directly manipulate any attribute outside of the helper methods that pyad provides:

user1 = ADUser.from_cn("myuser1") user.set_attribute("description", "new description") user.append_to_attribute("member", "cn=myuser1, ou=staff, dc=domain, dc=com") 

More details on how to manipulate the objects you find to is found in the next section.

Читайте также:  Apk to java machine

Creating, Moving, and Deleting Objects¶

There are two methodologies for creating and deleting objects. In both cases, you must first bind to the parent container. When creating a new object, several attributes are required, but other additional attributes can be specified with the optional_attributes parameter. Example 1:

ou = ADContainer.from_dn("ou=workstations, dc=domain, dc=com") # create a new group without any optional attributes new_computer = ADComputer.create("WS-489", ou) # create a new group with additional attributes new_group = ADGroup.create("IT-STAFF", security_enabled=True, scope='UNIVERSAL', optional_attributes = "description":"all IT staff in our company">) 

It is also possible to create new objects from the parent container:

ou = ADContainer.from_dn("ou=workstations, dc=domain, dc=com") computer = ou.create_computer("WS-490") 

Once objects are created, they can be moved:

computer = ADComputer.from_cn("WS-500") computer.move(ADContainer.from_dn("ou=workstations, ou=HR, dc=company, dc=com")) 
computer = ADComputer.from_cn("WS-500") computer.rename("WS-501") 

Objects can be removed by calling delete():

ADComputer.from_cn("WS-500").delete() 

Searching Active Directory¶

As shown above, objects can be directly connected to via CN, DN, GUID, or UPN. However, objects can also be searched for through the ADQuery interface (and in the background, this is how objects are actually found when you connect by CN). It is important to note that the ADQuery interface will not provide you with pyad objects, but instead with only the attributes for which you queried, for performance reasons. Example:

import pyad.adquery q = pyad.adquery.ADQuery() q.execute_query( attributes = ["distinguishedName", "description"], where_clause = "objectClass = '*'", base_dn = "OU=users, DC=domain, DC=com" ) for row in q.get_results(): print row["distinguishedName"] 

Источник

active_directory 0.67.1

Active Directory (AD) is Microsoft’s answer to LDAP, the industry-standard
directory service holding information about users, computers and
other resources in a tree structure, arranged by departments or
geographical location, and optimized for searching.

The Python Active Directory module is a lightweight wrapper on top of the
pywin32 extensions, and hides some of the plumbing needed to get Python to
talk to the AD API. It’s pure Python and should work with any version of
Python from 2.2 onwards (generators) and any recent version of pywin32.

When all’s said and done, it’s just a module. But for those
who like setup programs:

If you’re running a recent Python (2.2+) on a recent Windows (2k, 2k3, XP)
and you have Mark Hammond’s pywin32 extensions installed, you’re probably
up-and-running already. Otherwise.

Windows
——-
If you’re running Win9x / NT4 you’ll need to get AD support
from Microsoft. Microsoft URLs change quite often, so I suggest you
do this:
http://www.google.com/search?q=site%3Amicrosoft.com+active+directory+downloads

Python
——
http://www.python.org/ (just in case you didn’t know)

There are examples at: http://timgolden.me.uk/python/ad_cookbook.html
but as a quick taster, try this, to list all users’ display names:

for person in active_directory.search (objectCategory=’Person’):
print person.displayName

Источник

Оцените статью