User and Group Management
Category: Intermediate Linux Commands
Type: Linux Commands
Generated on: 2025-07-10 03:09:04
For: System Administration, Development & Technical Interviews
User and Group Management - Linux Cheatsheet (Intermediate)
Section titled “User and Group Management - Linux Cheatsheet (Intermediate)”This cheat sheet provides a comprehensive guide to user and group management commands in Linux. It caters to both sysadmins and developers, offering practical examples and advanced techniques.
1. Command Overview:
These commands allow you to manage user accounts and groups on a Linux system. This includes creating, modifying, deleting users and groups, as well as controlling their permissions and access rights. Proper user and group management is critical for system security, resource allocation, and collaboration.
2. Basic Syntax:
useradd [options] username- Create a new user.usermod [options] username- Modify an existing user.userdel [options] username- Delete a user.groupadd [options] groupname- Create a new group.groupmod [options] groupname- Modify an existing group.groupdel groupname- Delete a group.id [username]- Display user and group IDs.groups [username]- Display group memberships.chown [options] user:group file/directory- Change file/directory ownership.chgrp group file/directory- Change file/directory group ownership.
3. Practical Examples:
-
Creating a new user:
Terminal window sudo useradd -m -s /bin/bash developersudo passwd developer # Set the passwordExplanation: Creates a new user named
developerwith a home directory (-m) and sets the shell to/bin/bash(-s).passwdis then used to set the user’s password (root privilege required).Output: (No output from
useraddunless errors occur) Thepasswdcommand prompts for a new password. -
Adding a user to a group:
Terminal window sudo usermod -a -G www-data developerExplanation: Adds the
developeruser to thewww-datagroup (-aappends,-Gspecifies the group).Output: (No output unless errors occur)
-
Creating a new group:
Terminal window sudo groupadd developersExplanation: Creates a new group named
developers.Output: (No output unless errors occur)
-
Changing file ownership:
Terminal window sudo chown developer:developers /var/www/html/projectExplanation: Changes the owner of the
/var/www/html/projectdirectory todeveloperand the group todevelopers.Output: (No output unless errors occur)
-
Deleting a user (careful!):
Terminal window sudo userdel -r developerExplanation: Deletes the user
developerand removes their home directory (-r). WARNING: This is destructive! Back up data before deleting users.Output: (No output unless errors occur)
-
Displaying user information:
Terminal window id developerExplanation: Displays the user ID (uid), group ID (gid), and group memberships of the
developeruser.Example Output:
uid=1001(developer) gid=1001(developer) groups=1001(developer),27(sudo),33(www-data) -
Displaying group memberships:
Terminal window groups developerExplanation: Shows the groups the
developeruser belongs to.Example Output:
developer : developer www-data
4. Common Options:
useradd:-m: Create the user’s home directory.-s: Specify the user’s login shell (e.g.,/bin/bash,/bin/sh,/usr/sbin/nologin).nologindisables interactive login.-g: Specify the user’s primary group.-G: Specify supplementary groups (comma-separated).-u: Specify the user ID (UID). (Use with caution to avoid conflicts.)-d: Specify the home directory.-c: Add a comment or description for the user (e.g., full name).
usermod:-l: Change the user’s login name.-d: Change the user’s home directory. Use with-mto move the contents of the old home directory to the new one.-g: Change the user’s primary group.-G: Change the user’s supplementary groups.-aoption is crucial to append to existing groups, otherwise it replaces them.-s: Change the user’s login shell.-u: Change the user ID (UID). (Use with extreme caution.)-c: Change the user’s comment.-L: Lock the user’s account (disable login).-U: Unlock the user’s account (enable login).-e: Set an expiration date for the user account (YYYY-MM-DD).
userdel:-r: Remove the user’s home directory and mail spool. WARNING: This is destructive!
groupadd:-g: Specify the group ID (GID). (Use with caution.)
groupmod:-n: Change the group name.-g: Change the group ID (GID). (Use with caution.)
chown:-R: Recursive. Changes ownership of all files and subdirectories within a directory.--from=CURRENT_OWNER: Only change the owner if the current owner matches.
chgrp:-R: Recursive. Changes group ownership of all files and subdirectories within a directory.
5. Advanced Usage:
-
Creating a user with a specific UID and GID:
Terminal window sudo groupadd -g 1005 developerssudo useradd -u 1005 -g developers -m -s /bin/bash webadminsudo passwd webadminExplanation: Creates a group
developerswith GID 1005, then creates a userwebadminwith UID 1005 and primary groupdevelopers. Important: Be very careful when specifying UIDs and GIDs manually to avoid conflicts. -
Locking and unlocking user accounts:
Terminal window sudo usermod -L developer # Lock the accountsudo usermod -U developer # Unlock the accountExplanation:
-Llocks the account, preventing login.-Uunlocks it. -
Changing a user’s home directory and moving the contents:
Terminal window sudo usermod -d /new/home/developer -m developerExplanation: Changes the home directory of the
developeruser to/new/home/developerand moves the contents from the old home directory to the new one (-m). Ensure the new directory exists and has appropriate permissions. -
Using
findandchowntogether:Terminal window sudo find /var/www/html/project -type f -print0 | xargs -0 sudo chown developer:developerssudo find /var/www/html/project -type d -print0 | xargs -0 sudo chown developer:developersExplanation: This changes the ownership of all files and directories under
/var/www/html/projecttodeveloper:developers. The-print0andxargs -0combination handles filenames with spaces correctly. This is very useful for setting permissions on web application directories. -
Conditional Ownership Changes:
Terminal window sudo chown --from=root:root developer:developers /path/to/fileExplanation: This command will only change the ownership of
/path/to/filetodeveloper:developersif the current owner isroot:root. This is useful for preventing accidental changes when running scripts.
6. Tips & Tricks:
- Use meaningful usernames and group names. This improves readability and maintainability.
- Use strong passwords. Implement password policies if necessary (using
pam_pwquality.soin/etc/pam.d/common-password). - Limit sudo access. Only grant sudo privileges to users who truly need them. Use
visudoto edit the/etc/sudoersfile safely. - Regularly review user accounts and group memberships. Remove inactive accounts and ensure users have only the necessary permissions.
- Automate user and group management with scripts. This can save time and reduce errors.
- Use version control for your user and group management scripts. This allows you to track changes and revert to previous configurations if necessary.
- For web servers, always isolate web files and user accounts to prevent security breaches.
- Understand the difference between primary and supplementary groups. The primary group is used for creating new files and directories. Supplementary groups grant additional permissions.
7. Troubleshooting:
useradd: user 'username' already exists: The username is already taken. Choose a different username or delete the existing user (with caution!).useradd: group 'groupname' does not exist: The specified group does not exist. Create the group first.chown: invalid user: 'user:group': The user or group name is invalid or does not exist. Double-check the spelling.- Permission denied errors: You are likely missing
sudoor do not have sufficient privileges to perform the operation. - UID/GID conflicts: When manually specifying UIDs and GIDs, ensure they are not already in use. Check
/etc/passwdand/etc/group. - User cannot log in:
- Check the user’s password.
- Check the user’s shell (it should be a valid shell, not
/usr/sbin/nologinif login is required). - Check if the user’s account is locked (
usermod -U usernameto unlock). - Check if the user’s account has expired (
usermod -e YYYY-MM-DD usernameto set/modify expiration). - Check
/etc/shadowfor password related issues.
8. Related Commands:
passwd: Change user passwords.su: Switch user.sudo: Execute commands with superuser privileges.visudo: Edit the/etc/sudoersfile safely.getent: Get entries from Name Service Switch libraries (e.g.,getent passwd,getent group). Useful for querying user and group information.groups: Show the groups a user belongs to.id: Display user and group IDs.newgrp: Change the current group ID.pwck: Verify the integrity of password files.grpck: Verify the integrity of group files.acl: Access Control Lists (more fine-grained permissions).getfacl,setfacl.umask: Sets the default file permissions for new files.
This cheat sheet provides a solid foundation for managing users and groups in Linux. Remember to practice these commands in a safe environment (e.g., a virtual machine) before using them on a production system. Always back up your data before making significant changes.