How to add and remove Linux users
Topic: Servers linux
Summary
Create and delete user accounts with useradd and userdel (or adduser on Debian), set passwords and SSH keys, and assign users to groups. Use this to grant shell or SFTP access without sharing root and to clean up when someone leaves.
Intent: How-to
Quick answer
- Create: sudo useradd -m -s /bin/bash USER or adduser USER (Debian); set password with passwd USER; add key to ~/.ssh/authorized_keys.
- Add to group: usermod -aG GROUP USER; remove: userdel -r USER ( -r removes home). Check with id USER and groups USER.
- For service accounts use useradd -r -s /sbin/nologin; do not give login shell or password unless required.
Prerequisites
Steps
-
Create the user
useradd -m -s /bin/bash username (or adduser username); -m creates home, -s sets shell; use -r for system user without home if needed.
-
Set password and SSH key
passwd username; create ~/.ssh and authorized_keys with 700 and 600; append the public key so the user can log in with key auth.
-
Add to supplementary groups
usermod -aG group1,group2 username; groups username to verify; user needs to log out and back in for new groups to apply in session.
-
Remove a user
userdel username (no home removal) or userdel -r username (removes home); ensure no processes or cron jobs run as that user; move or archive data first if needed.
Summary
You will create and remove user accounts, set passwords and SSH keys, and manage group membership. Use this to give people or services access under their own account and to revoke access cleanly.
Prerequisites
- Root or sudo; shell access.
Steps
Step 1: Create the user
sudo useradd -m -s /bin/bash alice
# Debian/Ubuntu alternative
sudo adduser alice
Use -r for a system (service) account and omit -m if you do not want a home dir.
Step 2: Set password and SSH key
sudo passwd alice
sudo mkdir -p /home/alice/.ssh
sudo chmod 700 /home/alice/.ssh
echo "PUBLIC_KEY_LINE" | sudo tee -a /home/alice/.ssh/authorized_keys
sudo chmod 600 /home/alice/.ssh/authorized_keys
sudo chown -R alice:alice /home/alice/.ssh
Step 3: Add to supplementary groups
sudo usermod -aG docker,sudo alice
groups alice
User must log out and back in (or start new su/sudo session) for new groups to take effect.
Step 4: Remove a user
sudo pkill -u alice # stop their processes if any
sudo userdel -r alice
Use userdel alice without -r to keep the home dir; archive it first if needed for compliance.
Verification
- id alice shows correct uid, gid, groups; alice can log in via SSH with key; after userdel, id alice fails and home is gone if -r was used.
Troubleshooting
User is in use — userdel fails if processes or cron run as that user; pkill -u user or disable cron, then userdel.
Permission denied after adding to group — User must start a new login session for group membership to apply; use su - user or have them reconnect SSH.
Home directory wrong — Check /etc/passwd; fix with usermod -d /new/home; move files and set ownership.