import pwd
import grp

def enumerate_users_and_groups():
    # Enumerate users
    users = []
    for user in pwd.getpwall():
        username = user.pw_name
        uid = user.pw_uid
        groups = [g.gr_name for g in grp.getgrall() if username in g.gr_mem]
        users.append({'username': username, 'uid': uid, 'groups': groups})

    # Print user information
    for user in users:
        print('Username: ', user['username'])
        print('UID: ', user['uid'])
        print('Groups: ', user['groups'])
        print()

# Call the function to run the script
enumerate_users_and_groups()

This Python script effectively retrieves and displays user and group information from your system:

Explanation:

  1. Import Necessary Modules:

    • import pwd: Imports the 'pwd' module for interacting with the password database.
    • import grp: Imports the 'grp' module for working with the group database.
  2. Define enumerate_users_and_groups() Function:

    • users = []: Initializes an empty list to store user data.
    • for user in pwd.getpwall(): Iterates through each user entry obtained from pwd.getpwall().
      • username = user.pw_name: Extracts the username.
      • uid = user.pw_uid: Extracts the user ID (UID).
      • groups = [g.gr_name for g in grp.getgrall() if username in g.gr_mem]: Creates a list of group names to which the user belongs by iterating through all groups and checking membership.
      • users.append(...): Appends a dictionary containing the username, UID, and groups to the 'users' list.
  3. Print User Information:

    • for user in users:: Iterates through the collected user data.
      • print(...): Prints the username, UID, and groups for each user in a formatted way.
  4. Execute the Function:

    • enumerate_users_and_groups(): Calls the function to run the script.

Important Considerations:

  • Permissions: Running this script requires necessary permissions to access '/etc/passwd' and '/etc/group'.
  • Local Database: The script retrieves information from the local system database. Adapt it for network database equivalents if needed.
  • Modification: Feel free to modify the script to tailor the output or processing according to your specific requirements.
Python Script to Enumerate Users and Groups from /etc/passwd and /etc/group

原文地址: https://www.cveoy.top/t/topic/bFxG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录