I'm fairly new to Python and I am trying to Query an AD server and check to see if a User exists based on some attributes (username, firstName, lastName) and if that user exists query their groups to see if they are in a specific group and if not, add them to that group. I have a YAML file, where I'm storing the User's info, along with the group I want to add them in:
ADUser:
firstName: <value>
lastName: <value>
username: <value>
email: <value>
group: <value of group I want them to join>
Here is the code to parse the yaml file:
with open("AD.yaml", 'r') as stream:
try:
print(yaml.load(stream))
except yaml.YAMLError as exc:
print(exc)
I'm using the PyAD library to access AD and run my searches and User creation and group setting. Here is a link to the documentation: https://zakird.com/pyad/index.html
This is what I've started writing:
q = pyad.adquery.ADQuery()
q.execute_query(
attributes = (["firstName", <value>],["lastName", <value>],["username", <value>],["email", <value>])
where_clause = "objectClass = '*'",
base_dn = "OU=users, DC=domain, DC=com"
)
These are the methods I want to use for user creation, group adding and querying (I'm trying to figure out if these look good or not, and exactly how to use them with the YAML I currently have):
#User Creation
create_user(name, password=None, upn_suffix=None, enable=True, optional_attributes={})
#Find Members of a group
get_memberOfs(recursive=False, scope='all')ΒΆ
#Add an object to a group
add_to_group(group)
#Query AD
q = pyad.adquery.ADQuery()
q.execute_query(
attributes = ["distinguishedName", "description"],
where_clause = "objectClass = '*'",
base_dn = "OU=users, DC=domain, DC=com"
)
I'm just wondering if anyone can help point me to how this should be setup. Don't worry about accessing the actual AD server I'm just imagining running this from the box itself.
This is what I've done so far:
with open("AD.yaml", 'r') as stream:
try:
print(yaml.load(stream))
except yaml.YAMLError as exc:
print(exc)
def create_User(new_user, group, ):
q = pyad.adquery.ADQuery()
user = q.execute_query(
attributes = ["firstName", "description"],
where_clause = "objectClass = '*'",
base_dn = "OU=users, DC=domain, DC=com"
)
if user == true:
if user.is_member_of(group, "")
logging.info('User is already created and is member of Specified AD Group')
else
user.add_to_group(user, group)
else
new_user = ADUser.create("%firstName", "%lastname", "" )
group = ADGroup.from_dn(group)
group.add_member(new_user)