Skip to content

Instantly share code, notes, and snippets.

@luisdelatorre012
Created September 17, 2024 16:37
Show Gist options
  • Save luisdelatorre012/5aabf535ff6122a85e4427d31c082925 to your computer and use it in GitHub Desktop.
Save luisdelatorre012/5aabf535ff6122a85e4427d31c082925 to your computer and use it in GitHub Desktop.
ad group sync
import subprocess
import json
def run_powershell_command(command):
completed_process = subprocess.run(
["powershell", "-Command", command],
capture_output=True,
text=True
)
if completed_process.returncode != 0:
raise Exception(f"PowerShell command failed: {completed_process.stderr}")
return completed_process.stdout.strip()
def get_group_members(group_name):
command = f"Get-ADGroupMember -Identity '{group_name}' | Select-Object -ExpandProperty SamAccountName | ConvertTo-Json"
output = run_powershell_command(command)
return json.loads(output)
def add_user_to_group(user, group_name):
command = f"Add-ADGroupMember -Identity '{group_name}' -Members '{user}'"
run_powershell_command(command)
def remove_user_from_group(user, group_name):
command = f"Remove-ADGroupMember -Identity '{group_name}' -Members '{user}' -Confirm:$false"
run_powershell_command(command)
def sync_ad_group(group_name, user_list):
current_members = get_group_members(group_name)
# Handle the case where there's only one member (returned as a string instead of a list)
if isinstance(current_members, str):
current_members = [current_members]
# Add users who are in the list but not in the group
for user in user_list:
if user not in current_members:
print(f"Adding {user} to the group")
add_user_to_group(user, group_name)
# Remove users who are in the group but not in the list
for user in current_members:
if user not in user_list:
print(f"Removing {user} from the group")
remove_user_from_group(user, group_name)
print("Synchronization complete")
# Example usage
ad_group_name = "YourADGroupName"
user_list = ["user1", "user2", "user3"] # Replace with your actual list of users
if __name__ == "__main__":
try:
sync_ad_group(ad_group_name, user_list)
except Exception as e:
print(f"An error occurred: {str(e)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment