6. Users & Groups
6.1 User Management Commands
bash
# Add a user (Ubuntu recommends adduser for interactive setup)
sudo adduser john
# Or use useradd (requires manual password setup, etc.)
sudo useradd -m -s /bin/bash john
sudo passwd john
# Modify user information
sudo usermod -aG docker john # Add john to the docker group
sudo usermod -s /bin/zsh john # Change default shell
sudo usermod -L john # Lock account
sudo usermod -U john # Unlock account
# Delete a user
sudo userdel john # Delete user (keep home directory)
sudo userdel -r john # Delete user and home directorybash
$ sudo adduser john
Adding user `john' ...
Adding new group `john' (1001) ...
Adding new user `john' (1001) with group `john' ...
Creating home directory `/home/john' ...
Copying files from `/etc/skel' ...
New password:
Retype new password:
passwd: password updated successfully
Changing the user information for john
Enter the new value, or press ENTER for the default
Full Name []: John Smith
Room Number []:
Work Phone []:
Home Phone []:
Other []:
Is the information correct? [Y/n] Y6.2 Group Management
bash
# Create a group
sudo groupadd developers
# Add users to a group
sudo usermod -aG developers john
sudo usermod -aG developers jane
# View groups a user belongs to
groups john
id john
# Delete a group
sudo groupdel developersbash
$ id john
uid=1001(john) gid=1001(john) groups=1001(john),27(sudo),1002(developers)
$ groups john
john : john sudo developers6.3 Understanding /etc/passwd
bash
head -3 /etc/passwdbash
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
john:x:1001:1001:John Smith,,,:/home/john:/bin/bashEach line is separated by :, with 7 fields in total:
- Username: john
- Password placeholder: x (actual password is stored in /etc/shadow)
- UID: 1001 (User ID, 0 = root)
- GID: 1001 (Primary Group ID)
- Description: John Smith
- Home directory: /home/john
- Default shell: /bin/bash
6.4 sudo — Temporary Privilege Escalation
bash
# Execute a single command with root privileges
sudo apt update
# Switch to root user's shell
sudo -i
# Execute a command as another user
sudo -u www-data cat /var/www/html/index.html
# Edit the sudoers file (safe method)
sudo visudo⚠️ Note: ⚠️ Important: Never directly edit the /etc/sudoers file. Use the
visudocommand, which checks for syntax errors. Syntax errors could cause you to lose sudo access!
Common sudoers Configurations:
bash
# Allow john to use sudo without a password
john ALL=(ALL) NOPASSWD: ALL
# Allow the developers group to execute specific commands
%developers ALL=(ALL) /usr/bin/systemctl restart nginx