Skip to main content

Managing Linux Users, Groups and sudo

Manage Linux users, groups and sudo to enforce least-privilege access on shared production servers, with service accounts and audit commands.

30 Terms

Overview and What You Will Learn

Linux access control starts with identity: every process runs as a user, every file has an owner and a group, and every permission check asks who is asking. Users, groups and sudo are the tools that give each person and each service exactly the access it needs and nothing more.

By the end of this lab you will be able to:

  • Read /etc/passwd, /etc/shadow and /etc/group and explain every field
  • Create human accounts and non-login service accounts correctly
  • Manage group membership without accidentally removing existing groups
  • Write scoped sudo rules in /etc/sudoers.d/ and validate them safely
  • Offboard an account completely, including SSH key access
  • Audit who can log in and who can use sudo

Why This Matters in Production

Shared accounts destroy auditability. If five engineers share one deploy login, nobody can tell who dropped a production table, and revoking one person means changing everyone's access. Services running as root are just as risky, because one vulnerability in the service becomes a full server compromise. Picture a trading platform like Zerodha: nginx, PostgreSQL, a payment API and a log shipper all run on the same host, and a bug in the log shipper must not be able to read the payment API's database credentials. Separate users and groups are what enforce that boundary. The guiding rule is least privilege: the minimum access needed from day one, not broad access that you promise to restrict later.

Core Principles

Account data lives in three plain-text files. /etc/passwd holds identities, /etc/shadow holds password hashes and is readable only by privileged users, and /etc/group holds group membership.

YAML
root:x:0:0:root:/root:/bin/bash
deploy:x:1001:1001:Deploy User:/home/deploy:/bin/bash
nginx:x:999:999:nginx web server:/var/cache/nginx:/usr/sbin/nologin
payment-svc:x:998:998:Payment Service:/nonexistent:/usr/sbin/nologin
# /etc/group: groupname:x:GID:member1,member2
developers:x:1050:alice,bob,charlie
adm:x:4:syslog,deploy

The fields in /etc/passwd:

  • x means the password hash is stored in /etc/shadow
  • UID 0 is root and has total control of the system
  • The shell /usr/sbin/nologin (or /sbin/nologin on RHEL) blocks interactive login for service accounts

UID ranges follow a convention, and the exact boundaries are set in /etc/login.defs:

UID range Typical use
0 root
1 to 999 System and service accounts (boundaries vary by distro)
1000 and above Human accounts

su and sudo are often confused. su starts a shell as another user and needs that user's password. sudo runs one command with elevated rights, asks for your own password, and is controlled per user and per command by sudoers rules. Both are logged, but sudo records the exact command, which is why it is the standard for shared servers.

flowchart TD A([alice runs
sudo command]) --> B{Rule in
sudoers?} B -->|No| C[Denied and logged] B -->|Yes| D{Password
required?} D -->|Yes| E[Alice enters
her own password] D -->|No| F[Run as target user] E --> F F --> G[(Command logged
to auth log)] classDef start fill:#8B5CF6,color:#FFFFFF classDef check fill:#F1F5F9,color:#1E293B classDef bad fill:#EF4444,color:#FFFFFF classDef good fill:#10B981,color:#FFFFFF class A start class B,D check class C bad class E,F,G good

Detailed Step-by-Step Practical Lab

How to Check Which User and Groups You Are

Run id to see your UID, primary group and all supplementary groups, and getent to look up other accounts. getent is preferred over reading the files directly because it also covers accounts from LDAP or SSO.

Bash
whoami
# ubuntu
id
# uid=1000(ubuntu) gid=1000(ubuntu) groups=1000(ubuntu),4(adm),27(sudo)
# All users: name, UID and shell
getent passwd | cut -d: -f1,3,7 | column -t -s:
# All groups: name and GID
getent group | cut -d: -f1,3
# Who is logged in, and login history
who
w
last -n 20
lastlog | grep -v 'Never'
How to Create a User Account on Linux

Create the groups first, then the user, then set up key-based login. On Debian and Ubuntu the admin group is sudo; on RHEL, Rocky and Amazon Linux it is wheel. Check with getent group sudo wheel.

Bash
# Group must exist before you reference it
sudo groupadd developers
sudo useradd \
--create-home \
--shell /bin/bash \
--comment "Alice Engineer" \
--groups sudo,developers \
alice
# Verify
id alice
getent passwd alice
# Key-only access: install her public key (no password needed to log in)
sudo install -d -m 700 -o alice -g alice /home/alice/.ssh
echo 'ssh-ed25519 AAAAC3NzaC1lZDI1NTE5... alice@devops.in' | sudo tee /home/alice/.ssh/authorized_keys > /dev/null
sudo chown alice:alice /home/alice/.ssh/authorized_keys
sudo chmod 600 /home/alice/.ssh/authorized_keys

On Debian and Ubuntu, adduser alice is a friendlier interactive wrapper around useradd. Use the explicit useradd form in scripts and automation, because its behaviour is the same on every distribution.

How to Modify and Remove Linux Users Safely

Always use --append (-a) when adding a user to groups. Without it, usermod --groups replaces the whole supplementary group list.

Bash
# Add to a group WITHOUT removing existing groups
sudo usermod --append --groups developers alice
# Change shell or comment
sudo usermod --shell /bin/zsh alice
sudo usermod --comment "Alice - Platform" alice
# Remove from one group
sudo gpasswd -d alice developers
# Delete an account (--remove also deletes the home directory)
sudo userdel alice
sudo userdel --remove alice
Remember

usermod --groups docker alice without --append removes Alice from sudo, developers and every other supplementary group, leaving only docker.

Security

Membership of the docker group is effectively root access, because a user who can start containers can mount the host filesystem. Treat it with the same care as sudo.

How to Disable a Linux User Account When Someone Leaves

Locking the password is not enough. A locked password does not always stop SSH key login, depending on your PAM configuration, so lock the password, expire the account, remove the shell and delete the SSH keys.

Bash
# 1. Lock the password
sudo passwd --lock alice
# 2. Expire the account and remove its login shell
sudo usermod --expiredate 1 --shell /usr/sbin/nologin alice
# 3. Remove her SSH keys so key login cannot succeed
sudo rm -f /home/alice/.ssh/authorized_keys
# 4. End any live sessions
sudo pkill -KILL -u alice
# Check the result: status field shows L (locked)
sudo passwd -S alice
sudo chage -l alice

Also remove her from AllowUsers in the sshd configuration and from any sudoers files, and rotate shared credentials she had access to.

How to Create a Service Account for an Application

A service account is a non-human user that owns an application's files and runs its process. It has no password and no login shell, so it cannot be used for interactive access.

Bash
# --system: UID in the system range
# --no-create-home: the service does not need a home directory
# --shell nologin: no interactive login
sudo useradd \
--system \
--no-create-home \
--shell /usr/sbin/nologin \
--comment "Payment Service Account" \
payment-svc
id payment-svc
# Application directory owned by the service account
sudo mkdir -p /opt/payment-service
sudo chown payment-svc:payment-svc /opt/payment-service
sudo chmod 750 /opt/payment-service
# Interactive login is refused
sudo su - payment-svc
# This account is currently not available.
# Running a single command as the account still works
sudo -u payment-svc id

Then run the service with User=payment-svc in its systemd unit, so the process itself never runs as root.

How to Create Groups and Share Directories

A group lets several users share files. The setgid bit (2 in 2775) on a directory makes new files inherit the directory's group instead of the creator's primary group.

Bash
sudo groupadd developers
sudo groupadd --system deploy-access
# Add and remove members
sudo gpasswd -a bob developers
sudo gpasswd -d bob developers
# List members
getent group developers
# developers:x:1050:alice,bob
# Shared web directory: group-writable, new files inherit the group
sudo chgrp developers /var/www/html
sudo chmod 2775 /var/www/html
# Apply a new group in the current shell without logging out
newgrp developers

Group changes apply to new login sessions. Existing sessions keep the old groups until you log out and back in, or use newgrp.

How to Configure sudo with Scoped Rules

Give each person or group only the commands they need, and keep rules in separate files under /etc/sudoers.d/. Always edit with visudo, which checks the syntax before saving so a typo cannot lock everyone out of sudo.

Bash
# Create or edit a drop-in file (visudo sets safe permissions)
sudo visudo -f /etc/sudoers.d/deploy-access
# Check syntax of one file, and of the whole configuration
sudo visudo -cf /etc/sudoers.d/deploy-access
sudo visudo -c
# Find the real path of the command you are allowing
command -v systemctl
Bash
# who where=(as_whom) what
# A named admin with full sudo (password required)
alice ALL=(ALL:ALL) ALL
# A whole group gets sudo
%developers ALL=(ALL) ALL
# Scoped, passwordless rules for a deployment account: exact commands only
Cmnd_Alias PAYMENT_CMDS = /usr/bin/systemctl restart payment-service, \
/usr/bin/systemctl reload nginx
deploy ALL=(root) NOPASSWD: PAYMENT_CMDS
# AVOID: unrestricted passwordless sudo for a CI runner
# jenkins ALL=(ALL) NOPASSWD: ALL
Bash
# What is a user allowed to run?
sudo -l -U alice
# Run one command as a service account (shell not required)
sudo -u payment-svc /opt/payment-service/bin/check-config
# Open a shell as another user (use sparingly; it is harder to audit)
sudo -i -u deploy

Sudo ignores files in /etc/sudoers.d/ whose names contain a dot or end with ~, so name them like deploy-access and not deploy.conf. Avoid wildcards in command rules such as systemctl restart *: sudo wildcards also match arguments you did not intend, so list the exact commands instead.

Tip

One file per purpose, such as deploy-access or jenkins-ci, keeps rules easy to review and lets you remove a whole access path by deleting one file.

How to Audit Linux Users and sudo Access

Run the same audit on a schedule: who can log in, who has sudo, who used it, and who failed to log in. Log locations differ by distribution, so the journal is the portable option.

Bash
# Accounts with a real login shell
grep -v -E '/nologin$|/false$' /etc/passwd | cut -d: -f1
# Accounts with an empty password field (critical finding)
sudo awk -F: '($2 == "") {print $1}' /etc/shadow
# Who is in the admin group (sudo on Debian, wheel on RHEL)
getent group sudo wheel
# Passwordless and wildcard rules
sudo grep -rE 'NOPASSWD|\*' /etc/sudoers /etc/sudoers.d/
# What sudo has been used for (journal works on every systemd distro)
sudo journalctl _COMM=sudo --since "1 day ago" --no-pager | tail -20
# alice : TTY=pts/0 ; PWD=/home/alice ; USER=root ; COMMAND=/usr/bin/systemctl restart nginx
# Failed SSH logins (unit is ssh on Debian and Ubuntu, sshd on RHEL)
sudo journalctl -u ssh -g 'Failed password' --no-pager | tail -20
sudo lastb | head

On Debian and Ubuntu, sudo events are also in /var/log/auth.log; on RHEL based systems they are in /var/log/secure.

Production Best Practices & Common Pitfalls

  • One named account per person. It is the only way to audit actions and revoke access cleanly.
  • Never run services as root. Create a service account and set User= in the unit file.
  • Scope sudo to exact commands. Prefer full paths over wildcards, and avoid NOPASSWD: ALL except where there is no alternative.
  • Use drop-in files and visudo. Validate with visudo -c before you log out.
  • Offboard completely. Lock the password, expire the account, remove the shell and delete SSH keys.
  • Review quarterly. Check login shells, sudo rules and group membership whenever the team changes.
Mistake Problem Fix
Services run as root One exploit compromises the whole server Dedicated service account
Shared deploy login No audit trail, hard to revoke One named account per human
NOPASSWD: ALL for CI Runner compromise becomes root Exact command list
Editing /etc/sudoers by hand Syntax error can break sudo visudo and drop-in files
Only locking the password SSH keys may still work Expire account and delete keys
usermod -G without -a Existing groups are wiped usermod --append --groups

Quick Reference & Troubleshooting Commands

Task Command
Show my identity id
Look up an account getent passwd alice
Create a user sudo useradd --create-home --shell /bin/bash alice
Create a service account sudo useradd --system --no-create-home --shell /usr/sbin/nologin svc
Add to a group sudo usermod --append --groups developers alice
Lock a password sudo passwd --lock alice
Show account status sudo passwd -S alice
Edit sudo rules sudo visudo -f /etc/sudoers.d/name
Check sudo syntax sudo visudo -c
List a user's sudo rights sudo -l -U alice
Symptom First command What to look for
User cannot log in over SSH getent passwd alice Shell is nologin, or account expired
Permission denied despite sudo sudo -l -U alice Command or path not in the allowed list
Group change has no effect id alice User must log out and back in
sudo rule ignored ls -l /etc/sudoers.d/ File name has a dot or ~, or wrong mode (should be 0440)
Account seems locked sudo passwd -S alice Status field shows L

Resources

Explore More in Linux Fundamentals and File System

All 4 Topics

Frequently Asked Questions

Is Managing Linux Users, Groups and sudo free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Managing Linux Users, Groups and sudo topic cover?

Manage Linux users, groups and sudo to enforce least-privilege access on shared production servers, with service accounts and audit commands.

Found a mistake, an outdated step or a broken link?