1

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)
Bharel
  • 23,672
  • 5
  • 40
  • 80
user2019182
  • 295
  • 5
  • 19
  • Your posted Python was not correct, both `with` statements had no indented block. I assumed this was because of your infamiliarity with the formatting on this site and tried to correct it. If the result is not what you have on your computer, please roll-back the edit and/or put the correct code here. – Anthon Mar 18 '17 at 16:27

1 Answers1

2

You are loading the User's info, but you are only printing it. You should at least store it for further use. Apart from that there is absolutely no need to use the unsafe yaml.load()

from ruamel import yaml

with open("AD.yaml", 'r') as stream:
    try:
        data = yaml.load(stream)
        print(data)
    except yaml.YAMLError as exc:
        print(exc)

with that you can call your method:

 user = data['AdUser']
 create_User(user['username'], user['group'])

There are a few things to consider, apart from not using yaml.load():

  • in Python you should not use camel_case in methods you write yourself (some libraries conform to non-Pythonesc specific casing), so change create_User to create_user
  • add parameters to create_user for the other things you'll want to register (email, etc)
  • consider making the top-level of your file a sequence so you can iterate over the data loaded from YAML and register multiple users in one go

    - firstName: <value>
      lastName: <value>
      username: <value>
      email: <value>
      group: <value>
    - firstName: <value>
      lastName: <value>
      username: <value>
      email: <value>
      group: <value>
    

    and then do:

    for user in data:
        create_user(user['username'], user['group'])
    
Anthon
  • 69,918
  • 32
  • 186
  • 246
  • Thanks so much for your response! I incorporated some of your changes into my codebase. Do you have any comments on the if statements or the AD query that I have set up? I'm not sure if you have any suggestions for how to tweak some of that as well. – user2019182 Mar 18 '17 at 21:53
  • Sorry I am not so familiar with working with ActiveDirectory, so I didn't have much comment on that. This line `if user == true` requires `true` to be defined/imported, which looks a bit strange. Python has `True` but you would not test with `==` (or `is`), and then just do `if user:` – Anthon Mar 18 '17 at 21:59