ldap

Automating LDAP User Creation with Python

Posted on Updated on

This is an example of code from a Python script that I created to automate the addition of users to various LDAP groups.  Key functions of this script are as such:

  • Runs using arguments for username, first and last name (and outputs to the script runner what the valid options are).
  • Generates the next available UID automatically.
  • Allows for input of LDAP administrative password outside of the script, as an extra security precaution.
  • Menu-driven for ease of use. ¬†Allows for adding user based on role and will join the user to the appropriate groups.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import ldap
import ldap.modlist as modlist
import sys
import subprocess
import argparse

# Find next available UID
lastuid = subprocess.check_output('getent passwd | cut -d \':\' -f3 | sort -n | tail -1', shell=True)
nextuid = int(lastuid) + 1
uidnumber = str(nextuid)

# Argument checker
parser = argparse.ArgumentParser(description='Arguments for new user creation')
parser.add_argument("-u ", "--username", dest="username", required=True, help="username required")
parser.add_argument("-f ", "--FirstName", dest="firstname", required=True, help="First Name required")
parser.add_argument("-l ", "--LastName", dest="lastname", required=True, help="Last Name required")
args = parser.parse_args()

# Connection settings
server = "ldap://ldapserver.company.net:389"
user = "cn=manager"
passwd = raw_input("Enter the Manager password ")

# Other variables
fullname = (args.fircompanystname) + " " + (args.lastname)
netgroupname = "(," + (args.username) + ",)"
baseou = ""
defaultpw = "DefaultPassword"
### -NOTE- this should coincide with a policy that requires change upon first logon

# Group DN paths
developer_dn = "cn=developer,ou=Group,dc=company,dc=net"
splunk_developer_dn = "cn=splunk_developer,ou=Group,dc=company,dc=net"
web_dn = "cn=web,ou=Group,dc=company,dc=net"
admin_dn = "cn=admin,ou=Group,dc=company,dc=net"
splunk_admin_dn = "cn=splunk_admin,ou=Group,dc=company,dc=net"

# Add new user to the proper OU
def adduser():
    print (30 * '-')
    print (" What category user is this?")
    print (30 * '-')
    print ("1. Development")
    print ("2. Corporate")
    print ("3. Administrators")
    print ("4. QA")
    print ("5. Acme-Offshore")
    print (30 * '-')

## Get input ###
while True:
    choice = raw_input('Enter your choice [1-5] : ')
    if choice == "1":
        print ("Adding user to the .development OU...")
        baseou = ".development"
        dn = "uid="+(args.username)+",ou="+(baseou)+",ou=People,dc=company,dc=net"
        connect.add_s(dn,add_record)
        print ("Adding user to the appropriate additional groups...")
        devgroups()
        break
    elif choice == "2":
        print ("Adding user to the .corporate OU...")
        baseou = ".corporate"
        dn = "uid="+(args.username)+",ou="+(baseou)+",ou=People,dc=company,dc=net"
        connect.add_s(dn,add_record)
        break
    elif choice == "3":
        print ("Adding user to the .administrators OU...")
        baseou = ".administrators"
        dn = "uid="+(args.username)+",ou="+(baseou)+",ou=People,dc=company,dc=net"
        connect.add_s(dn,add_record)
        print ("Adding user to the appropriate additional groups...")
        admingroups()
        break
    elif choice == "4":
        print ("Adding user to the .qa OU...")
        baseou = ".qa"
        dn = "uid="+(args.username)+",ou="+(baseou)+",ou=People,dc=company,dc=net"
        connect.add_s(dn,add_record)
        break
    elif choice == "5":
        print ("Adding user to the .offshore, .acme OU...")
        baseou = ".acme"
        dn = "uid="+(args.username)+",ou="+(baseou)+",ou=.offshore,ou=People,dc=company,dc=net"
        connect.add_s(dn,add_record)
        break
    else:
    print ("Invalid number. Try again...")

# Add to development groups
def devgroups():
    connect.modify_s(developer_dn,mod_attrs)
    connect.modify_s(splunk_developer_dn,mod_attrs)
    connect.modify_s(web_dn,mod_attrs)

# Add to administrator groups
def admingroups():
    connect.modify_s(admin_dn,mod_attrs)
    connect.modify_s(splunk_admin_dn,mod_attrs)

# Add user record
add_record = [
  ("objectclass", ["person","organizationalPerson","inetorgPerson","top","posixAccount","shadowAccount"]),
  ("uid", [(args.username)]),
  ("cn", [(fullname)]),
  ("sn", [(args.lastname)]),
  ("givenName", [(args.firstname)]),
  ("userPassword", [(defaultpw)]),
  ("uidNumber", [(uidnumber)]),
  ("gidNumber", ["100"]),
  ("gecos", [(fullname)]),
  ("shadowMax", ["99999"]),
  ("shadowLastChange", ["99999"]),
  ("homeDirectory", ["/home/"+(args.username)]),
  ("mail", [(args.username)+"@company.com"]),
  ("loginShell", ["/bin/bash"]),
]

# Modify groups
mod_attrs = [
( ldap.MOD_ADD, 'memberUid', [(args.username)] )
]

# Open synchronous conection to LDAP
connect = ldap.initialize(server)
connect.simple_bind_s(user,passwd)

adduser()

# Print nice output
print ###############################
print "Username is: " + args.username
print "UID is: " + uidnumber
print "Password is: " + defaultpw
print ###############################

# Disconnect from LDAP server
connect.unbind_s()

Advertisements