Manage Users and Groups on Linux

Khimananda Oli 7 min read Virtualization
Manage Users and Groups on Linux

By Khimananda Oli | Last reviewed: August 2026

Properly configuring identity boundaries is the first line of defense in server hardening, yet misconfigured accounts remain a top cause of breaches. When you manage users and groups on Linux correctly, you enforce least-privilege access, simplify audits, and prevent accidental root exposure. This guide covers the exact commands, file structures, and security patterns I use daily to maintain compliant, production-grade systems.

User Account/etc/passwdUID + GIDHome Dir + ShellPrimary Group/etc/groupDefault OwnershipOne Per UserSecondary GroupsSupplementary AccessShared ResourcesMultiple AllowedFile PermissionsOwner (u)Group (g)Other (o)
Core architecture when you manage users and groups on Linux: accounts map to primary and secondary groups which determine file access

How do you create and modify users when you manage users and groups on Linux?

The distinction between useradd and adduser trips up many engineers new to server administration. useradd is the low-level binary present on all distributions; it does exactly what you tell it and nothing more. adduser is a Perl or shell wrapper (depending on distro) that interactively prompts for details and creates home directories automatically. For automation, infrastructure-as-code, and reproducible setups, always prefer useradd.

Creating a production-ready user account

A bare useradd username command often leaves accounts in an inconsistent state—no home directory, no shell, no groups. Use explicit flags to define the full identity boundary:

sudo useradd -m -s /bin/bash -c "Jane DevOps" -G sudo,docker jane
  • -m: Creates the home directory (/home/jane) and populates it from /etc/skel.
  • -s /bin/bash: Sets the login shell explicitly; without this, some distros default to /bin/sh or /usr/sbin/nologin.
  • -c: Adds a GECOS comment for audit trails and human identification.
  • -G: Assigns supplementary groups at creation time, avoiding a second usermod call.

After creation, set the password or lock the account if SSH key-only access is intended:

sudo passwd jane          # Interactive password set
sudo passwd -l jane       # Lock password auth (key-only)
sudo chage -M 90 jane     # Force password rotation every 90 days

In Nepal-based teams managing remote infrastructure, I frequently see accounts created without expiry dates. This becomes a compliance failure during SOC 2 audits. Always pair account creation with chage to enforce lifecycle policies.

Modifying existing accounts safely

Use usermod for changes, but understand its quirks. The -aG flag appends groups; using -G alone replaces the entire supplementary group list, which can accidentally revoke critical access:

# CORRECT: Append to existing groups
sudo usermod -aG www-data jane

# DANGEROUS: Replaces all supplementary groups
sudo usermod -G www-data jane

For renaming or UID changes, schedule maintenance windows. Active processes holding file descriptors under the old UID will not automatically update, leading to orphaned files and permission errors. For deeper context on securing these accounts after creation, refer to the Ubuntu security hardening guide.

What is the difference between primary and secondary groups in Linux?

Every Linux user has exactly one primary group and zero or more secondary groups. This distinction governs default file ownership and access inheritance, making it foundational when you manage users and groups on Linux.

AttributePrimary GroupSecondary Groups
Count per userExactly oneZero to many
Defined in/etc/passwd (GID field)/etc/group (member list)
New file ownershipDefault group ownerNot applied automatically
Typical usePersonal workspace isolationShared project/resource access
Change commandusermod -gusermod -aG

In practice, the primary group should be a private, user-named group (the UPG model). Shared resources like web roots, databases, or deployment directories should use secondary groups. This separation prevents accidental permission leakage when users create files in shared spaces.

Current Statejane: sudo, dockerusermod -aG www-dataSAFE: Appendusermod -G www-dataDANGER: ReplaceResult: sudo, docker, www-dataAccess preserved + addedResult: www-data ONLYsudo + docker REVOKED
Safe versus unsafe group modification when you manage users and groups on Linux: always use -aG to append

Managing group membership at scale

Create role-based groups before assigning users. This decouples access from individual accounts and simplifies onboarding/offboarding:

sudo groupadd webdeploy
sudo groupadd dbreadonly
sudo usermod -aG webdeploy,dbreadonly jane

Verify membership without parsing /etc/group manually:

id jane
groups jane
getent group webdeploy

For teams managing database access alongside OS accounts, aligning Linux groups with database roles reduces cognitive overhead. See the PostgreSQL administration essentials guide for mapping OS groups to DB roles securely.

How do you securely delete or disable Linux user accounts?

Deleting accounts is irreversible and risky. Disabling is almost always the better first step, especially during employee offboarding or incident response.

Disabling without data loss

  1. Lock the password: sudo passwd -l jane
  2. Expire the account immediately: sudo chage -E 0 jane
  3. Kill active sessions: sudo pkill -u jane
  4. Disable SSH keys: Rename or remove ~/.ssh/authorized_keys
  5. Document the action in your change log or ticketing system

This sequence preserves the home directory and mail spool for forensic review or data handover while preventing any further authentication.

Permanent deletion checklist

Only after confirming no legal hold, backup requirement, or open investigation exists should you run:

sudo userdel -r jane

The -r flag removes the home directory and mail spool. Without it, orphaned files remain owned by a now-nonexistent UID, creating security and cleanup headaches. Before deletion, audit for cron jobs, systemd timers, and running processes:

sudo crontab -u jane -l
sudo systemctl list-timers --all | grep jane
ps -u jane

For comprehensive pre-deletion server hygiene, the initial Ubuntu server setup guide covers baseline account policies that make future cleanup safer.

What are the best practices to audit and secure Linux user management?

Security is not a one-time configuration—it is continuous verification. When you manage users and groups on Linux in regulated environments, these practices separate compliant systems from vulnerable ones.

Inventory/etc/passwd/etc/groupValidateNo UID 0 except rootEmpty passwords checkSudo Audit/etc/sudoers.d/*Least privilege verifyInactive Scanlastlog > 90 daysLock or removeAutomate & ReportCron + SIEM integrationCompliance evidence
Continuous audit cycle when you manage users and groups on Linux: inventory, validate, scan, automate

Critical audit commands

Run these weekly or integrate them into your monitoring stack:

# Find accounts with UID 0 (should only be root)
awk -F: '$3 == 0 {print $1}' /etc/passwd

# Detect accounts with empty password fields
sudo awk -F: '($2 == "" || $2 == "!") {print $1}' /etc/shadow

# List users who have not logged in for 90+ days
sudo lastlog --before 90

# Verify sudoers syntax after edits
sudo visudo -c

Sudo configuration discipline

Never edit /etc/sudoers directly. Always use visudo or drop files into /etc/sudoers.d/ with restrictive permissions (0440). Grant specific commands, never blanket ALL=(ALL) NOPASSWD: ALL. For service accounts, consider using systemd's User= and DynamicUser=yes directives instead of persistent shell accounts.

Shadow file integrity

The /etc/shadow file stores password hashes and aging data. Ensure it is readable only by root (640 or 600). Any deviation indicates tampering or misconfiguration. Pair file permission checks with aide or tripwire for ongoing integrity monitoring, especially on servers handling financial or health data where Nepal's regulatory landscape increasingly mirrors global standards.

Secure Linux User Management as Operational Discipline

When you manage users and groups on Linux with rigor, you build infrastructure that survives audits, resists lateral movement, and scales with your team. The commands in this guide work on current stable releases of Ubuntu, Debian, RHEL, and AlmaLinux in 2026. Start by auditing your existing accounts today, then codify the patterns into Ansible playbooks or Terraform modules so drift cannot return. If your team needs help designing compliant identity architectures or preparing for SOC 2 evidence collection, reach out to discuss your infrastructure.

Frequently Asked Questions

Use useradd -m username to create the account and generate the home directory automatically. Set the password afterward with passwd username to activate login access for the new account.

useradd is a low-level binary suitable for scripts, while adduser is an interactive Perl wrapper that prompts for details and creates home directories by default on Debian-based systems.

Run usermod -aG groupname username to append the group without removing existing memberships. The -a flag is critical; omitting it overwrites current secondary group assignments entirely.

Execute userdel -r username to remove the account and delete the home directory plus mail spool. Always verify no running processes belong to that UID before deletion.

User accounts reside in /etc/passwd, passwords in /etc/shadow, and groups in /etc/group. Never edit these files directly; use vipw or vigr to prevent syntax corruption.

Use usermod -g newgroup username to reassign the primary group. Existing files owned by the old group remain unchanged; run chgrp recursively if ownership updates are required.

Type groups username or id username to display current group memberships. Note that changes made via usermod require a fresh login session to take effect in active shells.

Run passwd -l username to prefix the password hash with an exclamation mark, disabling password authentication. SSH key access may still work unless explicitly restricted in authorized_keys or sshd_config.

Yes, use useradd -e YYYY-MM-DD during creation or usermod -e YYYY-MM-DD for existing accounts. Check expiry status anytime with chage -l username to verify enforcement.

Configure pam_pwquality in /etc/security/pwquality.conf to require minimum length, complexity, and history. Apply settings globally through PAM stack configuration in /etc/pam.d/common-password on Debian or system-auth on RHEL derivatives.

Files retain their numeric UID ownership even after account removal. Orphaned files become security risks; find them using find / -nouser -nogroup and reassign or archive before creating new accounts.

Run useradd -r -s /usr/sbin/nologin servicename to create a non-login system account. The -r flag assigns a low UID range, and nologin prevents interactive shell access securely.

newgrp requires the target group be listed in your supplementary groups or have no password set. Add yourself via usermod -aG first, then log out and back in to refresh credentials.

Review /var/log/auth.log or /var/log/secure for useradd, usermod, and groupadd entries. Enable auditd rules for /etc/passwd and /etc/shadow to capture granular change events with timestamps.

Use newusers with a properly formatted input file matching /etc/passwd syntax. Validate the file first with pwck, test on a non-production system, and always backup shadow files beforehand.