Post

Python and Active directory

I have always used PowerShell when interacting with Active Directory for various tasks. I have been using Python more and more when working in Azure and wanted to try interacting with AD.

In this example I have tested creating a computer object under a specified OU and a group in another OU, and then added the computer object to the group.

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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import os
from ldap3 import Server, Connection, SIMPLE, MODIFY_ADD, SAFE_SYNC
from ldap3.extend.microsoft.addMembersToGroups import ad_add_members_to_groups

#Need to specify ip because i don't have DNS between my workstation and Lab AD.  
example_domain_dns_name = 'homelab.example.com'
local_ldap_ip = '192.168.5.20'

# Read password from environment variable
password = os.getenv('AD_PASSWORD')
user = os.getenv('AD_ADMIN')

# Check if password was found
if not password:
    raise ValueError("AD_PASSWORD environment variable not set!")
if not user:
    raise ValueError("AD_ADMIN environment variable not set!")

# Create server without TLS
server = Server(local_ldap_ip, port=389, use_ssl=False, get_info='ALL')

# Create connection
conn = Connection(
    server,
    user=f'homelab\\{user}',
    password=password,
    authentication=SIMPLE,
    auto_bind=True,
    client_strategy=SAFE_SYNC,
)

print("Connected successfully!")

# 1. CREATE A NEW COMPUTER OBJECT
computer_name = 'TESTPC01'
computer_dn = f'CN={computer_name},OU=Computers,OU=Stockholm,OU=SWE,DC=homelab,DC=example,DC=com'

computer_attributes = {
    'objectClass': ['top', 'person', 'organizationalPerson', 'user', 'computer'],
    'cn': computer_name,
    'sAMAccountName': f'{computer_name}$',  # Computer accounts end with $
    'userAccountControl': 4096,  # WORKSTATION_TRUST_ACCOUNT
    'dnsHostName': f'{computer_name}.homelab.example.com'
}

try:
    conn.add(computer_dn, attributes=computer_attributes)
    if conn.result['result'] == 0:
        print(f"✓ Computer '{computer_name}' created successfully!")
    else:
        print(f"✗ Failed to create computer: {conn.result['description']}")
except Exception as e:
    print(f"Error creating computer: {e}")

# 2. CREATE A NEW GROUP
group_name = 'TestGroup'
group_dn = f'CN={group_name},OU=Groups,OU=Stockholm,OU=SWE,DC=homelab,DC=example,DC=com'

group_attributes = {
    'objectClass': ['top', 'group'],
    'cn': group_name,
    'sAMAccountName': group_name,
    'groupType': -2147483646  # Global security group
}

try:
    conn.add(group_dn, attributes=group_attributes)
    if conn.result['result'] == 0:
        print(f"✓ Group '{group_name}' created successfully!")
    else:
        print(f"✗ Failed to create group: {conn.result['description']}")
except Exception as e:
    print(f"Error creating group: {e}")

# 3. OPTIONAL: Add the computer to the group
try:
    ad_add_members_to_groups(conn, computer_dn, group_dn)
    print(f"✓ Added {computer_name} to {group_name}")
except Exception as e:
    print(f"Error adding computer to group: {e}")

conn.unbind()
This post is licensed under CC BY 4.0 by the author.