How to Add and Delete Users on CentOS / Ubuntu: A Comprehensive Guide

Introduction
Managing user accounts is an essential task for system administrators, whether you’re using CentOS / RedHat or Ubuntu / Debian as your operating system. Adding and deleting users is a routine part of system administration and helps ensure the security and proper access control on your server. This article, "How to Add and Delete Users on CentOS / Ubuntu: A Comprehensive Guide," will provide you with a step-by-step guide on how to add and delete users on both CentOS and Debian. We will also explore alternative methods for achieving the same results.
I. Adding Users
1 – Adding users on CentOS
To add a user on CentOS, you can use the useradd
command. This command creates a new user account on the system.
$ sudo useradd john
After creating the user, you need to set a password for them. The passwd
command is used for this purpose.
$ sudo passwd john
You will be prompted to enter and confirm the password.
To add the user to a specific group, you can use the usermod
command. This allows you to grant the user specific permissions and access rights.
$ sudo usermod -aG groupname john
Replace “groupname” with the desired group name and “john” with the username.
Finally, to switch to the newly created user account, you can use the su
command.
$ sudo su - john
You will be prompted to enter the password for the user.
2 – Adding users on Debian
Adding a user on Debian is similar to CentOS, but utilizes the adduser
command, which is a more interactive tool.
$ sudo adduser john
You will be prompted to set a password and enter additional user information, such as the user’s full name, room number, work phone, and home phone. These are optional and can be left blank.
To switch to the newly created user account, you can use the su
command, just as in CentOS.
$ sudo su - john
Enter the password for the user to access the account.
II. Granting Sudo Privileges to a Users
1 – Granting Sudo Privileges to a User on CentOS
If you want to give your new user the ability to execute commands with root (administrative) privileges, you need to grant them access to sudo
.
One way to do this is by adding the user to the wheel group, which automatically provides sudo
access to all its members.
To add the user to the wheel group, use the usermod
command:
$ sudo usermod -aG wheel john
Now, your new user can execute commands with administrative privileges. Simply prepend sudo
before the command you want to run as an administrator:
$ sudo some_command
You will be prompted to enter your user account password (not the root password). After entering the correct password, the command will be executed with root privileges.
2 – Granting Sudo Privileges to a User on Debian
If you want to enable your new user to execute commands with root (administrative) privileges, you can grant them access to sudo
. There are two approaches to accomplish this: adding the user to the pre-defined sudo group or specifying privileges on a per-user basis in the sudo
configuration.
Adding the User to the Sudo Group
By default, sudo
on Debian systems is configured to grant full privileges to any user in the sudo group.
You can check which groups your new user belongs to using the groups
command:
$ sudo groups john
Output:
john : john
By default, a new user is only in their own group, which is created by adduser
and shares the same name as the user. To add the user to a different group, you can utilize the usermod
command:
$ sudo usermod -aG sudo john
The -aG
option tells usermod
to add the user to the specified groups.
Keep in mind that the usermod
command itself requires sudo
privileges. Therefore, you can only add users to the sudo
group if you are logged in as the root user or as another user who is already a member of the sudo
group. In the latter case, you will need to precede the command with sudo
, as shown in the example:
$ sudo sudo usermod -aG sudo john
III. Deleting Users
1 – Deleting users on CentOS
To delete a user on CentOS, you can use the userdel
command.
$ sudo userdel john
This command will delete the user account, but it will not remove the user’s home directory and associated files. To remove the home directory as well, use the -r
option.
$ sudo userdel -r john
2 – Deleting users on Debian
To delete a user on Debian, you can use the deluser
command.
$ sudo deluser john
This command will delete the user account and prompt you whether you want to remove the user’s home directory. To remove the home directory without being prompted, use the --remove-home
option.
$ sudo deluser --remove-home john
Conclusion
Managing user accounts is crucial for maintaining a secure and well-organized system. In this article, "How to Add and Delete Users on CentOS / Ubuntu: A Comprehensive Guide," we have provided you with a detailed guide on how to add and delete users on both CentOS and Debian. By following the step-by-step instructions, you can efficiently manage user accounts, assign proper access privileges, and ensure the security of your server. Remember to exercise caution when deleting users, as it can result in the loss of their associated files and data. Always have a backup and double-check your actions before proceeding.
By understanding these user management procedures, you’ll be able to handle user accounts effectively, maintaining a secure and organized server environment.
Alternative Solutions for User Management
While the useradd
/adduser
and userdel
/deluser
commands are the standard tools for user management, alternative methods exist, particularly when dealing with more complex scenarios or needing automation. Here are two different ways to solve the problem presented in the article:
1. Using Configuration Management Tools (Ansible):
Configuration management tools like Ansible are designed to automate system administration tasks, including user management. Instead of running individual commands, you define the desired state of your system in a playbook, and Ansible ensures that your system conforms to that state.
-
Explanation: Ansible uses YAML-based playbooks to define tasks. You can create a playbook that adds or removes users, sets passwords, and manages group memberships. This approach is especially useful when managing multiple servers or requiring consistent user configurations across your infrastructure. The idempotency of Ansible ensures that the playbook only makes changes when necessary, preventing unintended modifications.
-
Code Example (Ansible Playbook):
--- - hosts: all become: true tasks: - name: Add user 'john' user: name: john comment: John Doe password: "$6$rounds=656000$SaltString$HashedPassword" # Generate using mkpasswd or similar groups: sudo append: yes when: ansible_distribution == "Debian" or ansible_distribution == "Ubuntu" - name: Add user 'john' on CentOS user: name: john comment: John Doe password: "$6$rounds=656000$SaltString$HashedPassword" # Generate using mkpasswd or similar groups: wheel append: yes when: ansible_distribution == "CentOS" - name: Remove user 'john' user: name: john state: absent remove: yes
Explanation of the Playbook:
hosts: all
: Specifies that the playbook applies to all hosts in your Ansible inventory.become: true
: Indicates that the tasks require root privileges (sudo).tasks:
: A list of tasks to be executed.user:
: The Ansible module for managing user accounts.name
: The username.comment
: The user’s full name (optional).password
: The hashed password (important for security; generate securely).groups
: A list of groups the user should belong to.append: yes
: Add the user to the groups instead of replacing existing groups.state: absent
: When present, remove the user.remove: yes
: When deleting, also remove the user’s home directory.
when:
: Conditional execution based on the operating system distribution. This allows the same playbook to work on both Debian/Ubuntu and CentOS.
To use this playbook, you would save it as a
.yml
file (e.g.,user_management.yml
) and run it using theansible-playbook
command:ansible-playbook user_management.yml
2. Using a Script with getent
for User Existence Checks:
Instead of directly using useradd
and userdel
, you can create a script that first checks if the user exists using getent
before attempting to add or delete the user. This can help prevent errors and make your script more robust.
-
Explanation: The
getent
command retrieves entries from administrative database(s). By usinggetent passwd <username>
, you can check if a user with the specified username exists. The script then uses conditional logic to either add the user if they don’t exist or delete them if they do, handling potential errors gracefully. -
Code Example (Bash Script):
#!/bin/bash username="$1" action="$2" # "add" or "delete" if [ -z "$username" ] || [ -z "$action" ]; then echo "Usage: $0 <username> <add|delete>" exit 1 fi user_exists=$(getent passwd "$username") if [ "$action" == "add" ]; then if [ -z "$user_exists" ]; then echo "Adding user: $username" sudo adduser "$username" # Or useradd on CentOS, adjust as needed else echo "User $username already exists." fi elif [ "$action" == "delete" ]; then if [ ! -z "$user_exists" ]; then echo "Deleting user: $username" sudo deluser --remove-home "$username" # Or userdel -r on CentOS, adjust as needed else echo "User $username does not exist." fi else echo "Invalid action: $action. Must be 'add' or 'delete'." exit 1 fi exit 0
Explanation of the Script:
- The script takes the username and action (add or delete) as command-line arguments.
- It uses
getent passwd "$username"
to check if the user exists. The output ofgetent
will be empty if the user doesn’t exist. - Based on the
action
and the existence of the user, it either adds the user usingadduser
(Debian/Ubuntu) oruseradd
(CentOS) or deletes the user usingdeluser --remove-home
(Debian/Ubuntu) oruserdel -r
(CentOS). - It includes error handling for invalid input and non-existent users.
To use this script, save it as a
.sh
file (e.g.,manage_user.sh
), make it executable, and run it with the username and action as arguments:chmod +x manage_user.sh sudo ./manage_user.sh john add sudo ./manage_user.sh jane delete
These alternative methods provide more advanced and flexible approaches to user management, particularly in larger or more complex environments. While "How to Add and Delete Users on CentOS / Ubuntu: A Comprehensive Guide" covers the fundamental commands, these alternatives offer scalability and robustness.