Python – Remove Specific AD groups From Target Users

We have received a requirement where we need to remove a specific AD group from certain users.

Sharing a Python Script Sample which you can modify according to your needs.

I have deliberately used Python instead of Powershell for this magic to Sharpen my Python skills and also to assist Python lovers.

Modules required:

  • LDAP3 – For Active directory operations
  • DPAPI – For Password encryption/Decryption
  • VSADMIN – This I have built same as PowerShell vsadmin module and is uploaded to github.

Rest all modules are already part of Python package so not mentioning those.

Download the Script from GitHUB.

  • (place it in lib folder)

I have stored the userid, encrypted password and variables like email, smtp in config file so I have used configparser to extract those.

Some Important things to understand in the code:

Groupsuffix is the naming convention of the group we are interested in.

There can be multiple groups that start with this group prefix (I wrongly mentioned the variable as suffix) so if any of the group is found on the user it should be removed.

rshOUString is the string for OU to target only those OUs that contain that string.

Obj_filter is the query to get all enabled users in AD that have proxy address or Employeeid.

Group_filter is the query for finding all the groups starting with VS-PGWP-*

Another important aspect is in below code where we are excluding TEST users and getting the research OU users as we are targeting only those users.

We have utilized lambda here which is assisting us in filtering the fetched data.

In Next part of the Script, We are fetching users that are member of PWGP groups when found we have added a Break in loop and collected all the fetched users in groupcoll collection.

In the final part of the script We have added a threshold for removal of group from users for security reasons so in case we found more groups then usual we can check what’s wrong by coordinating with different IT department. You can change the threshold variable countofchanges as per your needs.

Although this can be environment specific, but I hope this Python magic will assist you after some modifications.


Thanks for reading and downloading…

Tech Wizard

PowerShell Fast Track


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s