#!/usr/bin/python3
import subprocess
import json
# Modify this path to the full path of your pveum executable
PVEUM_PATH = "/usr/sbin/pveum"
# Function to list users from Proxmox, filter, and update group membership
def list_and_update_users(group_name, realm_type, domain, ask_confirmation=True, silent=False):
# Command to list all users from Proxmox VE in JSON format
list_users_command = f"{PVEUM_PATH} user list --full --output-format json"
# Execute the command and capture the output
result = subprocess.run(list_users_command, shell=True, capture_output=True, text=True)
if result.returncode != 0:
if not silent:
print(f"Error listing users: {result.stderr}")
return
# Load JSON data from the command output
users_data = json.loads(result.stdout)
# Filter users based on the criteria
users_to_add = [
user['userid'] for user in users_data
if user.get('realm-type') == realm_type and
group_name not in user.get('groups', '') and
user['userid'].endswith(domain)
]
# Check if the filtered list is empty
if not users_to_add:
if not silent:
print("No users found meeting the search criteria.")
return
# Display users to be added unless silent
if not silent:
print("\nUsers to be added to group '{}':".format(group_name))
print(users_to_add)
# Check if confirmation is needed
if ask_confirmation and not silent:
response = input("Do you want to add these users to the group '{}'? (y/n): ".format(group_name))
if response.lower() != 'y':
print("No changes made.")
return
# Proceed to add users to the group
for user in users_to_add:
add_user_command = f"{PVEUM_PATH} usermod {user} -group {group_name}"
add_result = subprocess.run(add_user_command, shell=True, capture_output=True, text=True)
if add_result.returncode != 0 and not silent:
print(f"Failed to add {user} to group '{group_name}': {add_result.stderr}")
if not silent:
print("Operation completed.")
# params
group_name = "ProxmoxGroup" #this is the proxmox group you want to add the users to
realm_type = "ad"
domain = "@domain" #this is the part after the username for the realm, e.g. user@realm
# For interactive use
list_and_update_users(group_name, realm_type, domain, ask_confirmation=True, silent=False)
# For cron job or automated script
# list_and_update_users(group_name, realm_type, domain, ask_confirmation=False, silent=True)