Wednesday 20 June 2012

Python: Let Domain User's manage themselves

Not sure if that's a great idea ;)

I am always trying to find ways to help the 1st level support guys, they get lots of calls and when the calls pile up, I remember it being quite annoying.

So here is what I created.  Hope you enjoy!  Now obviously you need to make a few changes to make it work for you, but this little tool allows domain users with little access the ability to Add/ Remove users from groups that they are managers of. 




Heres what you need:

Active Directory;
User account; must be a member of the group as well as selected in the Managed By tab, check the box that says Manager can update the group and you are set.

*note I have images in the current directory, so be sure to change those around as well.
'''
Created on Jun 14, 2012

@author: rcummins
'''
import active_directory as AD
from Tkinter import *
from os import environ
import ttk
import win32com, win32com.client
import pythoncom
import tkMessageBox
from PIL import Image, ImageTk

login = environ["USERNAME"]
manager = []
 
LOGIN = AD.find_user(login)
grps = {}
for group in LOGIN.memberOf:
    GROUP = AD.AD_object(group)
    if str(LOGIN)[7:] == str(GROUP.managedby):
        GRP = AD.AD_object(group)
        grps[GRP.cn] = GRP.distinguishedName
        manager.append(str(GRP.cn))
   
root = Tk()
root.title("Manager Console")

root.wm_iconbitmap('mgmt.ico')


master = PanedWindow(orient=VERTICAL)
master.pack(fill=BOTH, expand=1)

userframe = LabelFrame(master, text='Groups Managed By: %s'%(LOGIN.cn))

fr = Frame(userframe)
userinfo = Label(fr, text='Manager of: ')
userinfo.pack(side=LEFT, padx=5, pady=10)
usergroups = ttk.Combobox(fr, values=manager, width=30)
usergroups.pack(side=LEFT, fill=X, expand=1, padx=5)

type=None
if(len(manager)>0):
    usergroups.set(manager[0])
    ggrp = AD.find_group(manager[0])
    type = AD.AD_object(ggrp)
grouptype = Label(userframe, text="No group(s) found..")
if(type):
    grouptype = Label(userframe, text="Description: %s"%(ggrp.description))
fr.pack(side=TOP)
grouptype.pack(side=TOP, padx=5)
master.add(userframe)

groupframe = LabelFrame(master, text='Group Detail and Modification')
groupinfo = Listbox(groupframe, height=20, width=30)
groupinfo.pack(side=LEFT, padx=5, pady=10)
controlframe = Frame(groupframe)
controlframe.pack(side=LEFT, padx=5, fill=BOTH)

master.add(groupframe)
def ADDUser(event=None):
    geo = root.winfo_pointerxy()
    xx = geo[0]
    yy = geo[1]
   
   
    TOPr = Toplevel()
    TOPr.title("Add a user to this group")
    TOPr.geometry("+%d+%d"%(xx,yy))
   
    x = Label(TOPr, text="Enter username:")
    x.pack(side=TOP, fill=X, padx=10)
    f = Frame(TOPr)
    em = Label(f, text="@WORK.com")
    em.pack(side=RIGHT)
    uname = Entry(f, width=15)
    uname.pack(side=RIGHT)
    f.pack(side=TOP, padx=10)
       
    def plusONE(event=None):
        if len(str(uname.get()))>0:
            usr = AD.find_user(str(uname.get()).strip())
            grp = AD.find_group(str(usergroups.get()).strip())
            uLDAP = "LDAP://%s"%(str(usr.distinguishedName))
            gLDAP = "LDAP://%s"%(str(grp.distinguishedName))
            try:
                grp_obj = win32com.client.GetObject(gLDAP)
                grp_obj.Add(uLDAP)
                #grp_obj.Remove(uLDAP)
                grp_obj.SetInfo()
                groupinfo.insert(END, usr.cn)
            except pythoncom.com_error,( hr,msg,exc,arg ):
                print "Error adding user %s to group %s..." % (usr.cn, grp.cn)
                print hr, msg, exc, arg
            #http://code.activestate.com/recipes/511447-add-account-to-group-in-active-directory/
    addButton = Button(TOPr, text='Add User', command=plusONE)
    addButton.image = photo
   
    addButton.pack(side=TOP, fill=X)
    root.update()
    TOPr.mainloop()

img = Image.open(r"business_user.png")
photo = ImageTk.PhotoImage(img)
addBTN = Button(groupframe, compound=TOP, image=photo, text='Add User', command=ADDUser)
addBTN.pack(side=TOP)


def DELUser(event=None):
    usr = AD.find_user(str(groupinfo.selection_get()).strip())
    grp = AD.find_group(str(usergroups.get()).strip())
    uLDAP = "LDAP://%s"%(str(usr.distinguishedName))
    gLDAP = "LDAP://%s"%(str(grp.distinguishedName))
    try:
        grp_obj = win32com.client.GetObject(gLDAP)
        #grp_obj.Add(uLDAP)
        xray = tkMessageBox.askokcancel("Delete User from Group", "Are you sure you want to delete: %s from %s"%(usr.cn, grp.cn))
        print xray
        if(xray):
            grp_obj.Remove(uLDAP)
            grp_obj.SetInfo()
    except pythoncom.com_error,( hr,msg,exc,arg ):
        print "Error adding user %s to group %s..." % (usr.cn, grp.cn)
        print hr, msg, exc, arg
        #http://code.activestate.com/recipes/511447-add-account-to-group-in-active-directory/
    root.update()
    groupname = usergroups.get()
    usrs = []
    for groupmbr in AD.find_group(groupname).member:
        usrs.append(str(groupmbr.cn))
    usrs.sort()
    groupinfo.delete(0, END)
    for usrer in usrs:
        if usrer != usr.displayName:
            groupinfo.insert(END, usrer)
    return

img2 = Image.open(r"business_user_delete.png")
photo2 = ImageTk.PhotoImage(img2)
delBTN = Button(groupframe, compound=TOP, image=photo2, text='Remove User', command=DELUser)
delBTN.pack(side=TOP)

master.add(groupframe)

def SelectDropdown(event=None):
    if(usergroups.get()):
        groupname = usergroups.get()
        usrs = []
        for groupmbr in AD.find_group(groupname).member:
            usrs.append(str(groupmbr.cn))
        usrs.sort()
        groupinfo.delete(0, END)
        for usrer in usrs:
            groupinfo.insert(END, usrer)
        root.update()
usergroups.bind("<<ComboboxSelected>>", SelectDropdown)
SelectDropdown()
root.mainloop()

As always, I accept constructive feedback, so if it could be cleaner, please let me know! always looking for feedback.

No comments:

Post a Comment