CommandsLinux

How to List Users on Linux

List Users on Linux

Managing user accounts is a fundamental skill for Linux system administrators, DevOps engineers, and anyone responsible for maintaining server security. Whether you’re conducting a security audit, troubleshooting permission issues, or simply need to know which accounts exist on your system, understanding how to list users on Linux is essential. The Linux operating system stores user information in specific system files, primarily the /etc/passwd file, which serves as the central database for all user accounts. This comprehensive guide explores multiple proven methods to view, filter, and manage user listings on any Linux distribution, from Ubuntu and CentOS to Fedora and Debian.

Understanding Linux User Accounts

The /etc/passwd File Structure

At the heart of Linux user management lies the /etc/passwd file. This plain-text configuration file contains essential information about every user account on the system. Each line in /etc/passwd represents a single user account and consists of seven colon-separated fields that define the user’s characteristics.

Here’s what a typical entry looks like:

meilana:x:1001:1001:Meilana Maria,,,:/home/meilana:/bin/bash

Breaking down these seven fields:

  1. Username (meilana): The login name used to access the system
  2. Password placeholder (x): The “x” indicates the encrypted password is stored securely in /etc/shadow
  3. User ID or UID (1001): A unique numerical identifier for the user
  4. Group ID or GID (1001): The primary group identifier
  5. GECOS field (Meilana Maria): Contains the user’s full name and additional contact information
  6. Home directory (/home/meilana): The user’s personal directory for storing files
  7. Login shell (/bin/bash): The command interpreter that launches when the user logs in

The /etc/passwd file is readable by all users on the system, but only the root user can modify it. The password field shows “x” because actual encrypted passwords are stored in the more secure /etc/shadow file, which has restricted read permissions.

Types of Linux Users

Linux distinguishes between two primary categories of user accounts, each serving different purposes within the system.

System Users are created automatically during operating system installation or when installing software packages. These special accounts run system services and background processes. System users typically have UIDs ranging from 0 to 999, with UID 0 always reserved for the root superuser account. Examples include www-data for web servers, mysql for database services, and mail for email handling. Most system users cannot log in interactively and have their shell set to /usr/sbin/nologin or /bin/false for security.

Regular Users represent actual people who interact with the system. Created by system administrators, these accounts have UIDs starting from 1000 (or 500 on some older distributions). Regular users can log in, access graphical interfaces, and work with files in their home directories. They typically have standard shells like /bin/bash or /bin/zsh assigned to them.

Method 1: Using the cat Command

The simplest and most straightforward method to list users on Linux uses the cat command to display the contents of /etc/passwd. This approach requires no special permissions and works on every Linux distribution.

Execute this command in your terminal:

cat /etc/passwd

The output displays all user accounts, both system and regular users, with complete details across all seven fields. While this method shows comprehensive information, it can be overwhelming on systems with many users.

To search for a specific user, combine cat with grep:

cat /etc/passwd | grep username

For case-insensitive searches, add the -i flag:

cat /etc/passwd | grep -i john

You can count the total number of user accounts using the word count utility:

cat /etc/passwd | wc -l

This command counts all lines in the file, giving you the total number of users. The cat command excels at quick checks and when you need to see complete user information without filtering. However, on production servers with hundreds of users, scrolling through the entire output becomes impractical.

Method 2: Using Terminal Pagers (less and more)

When dealing with lengthy user lists, pager utilities provide better navigation and readability. These tools display content one screen at a time, making it easier to browse through large files.

Using the less Command

The less pager offers powerful navigation features:

less /etc/passwd

Once the file opens in less, you can navigate using these keyboard shortcuts:

  • Arrow keys: Move up and down one line
  • Space bar: Jump forward one full screen
  • b key: Move backward one full screen
  • / key: Search forward (type your search term and press Enter)
  • ? key: Search backward
  • q key: Quit and return to the terminal

The less command allows bidirectional scrolling and includes robust search functionality, making it the preferred choice for exploring user databases. You can search for specific usernames by pressing / followed by the username, and press n to find the next occurrence.

Using the more Command

The more command provides similar functionality but with limitations:

more /etc/passwd

Unlike less, more only scrolls forward. Press the space bar to advance to the next screen. While more lacks backward navigation, it’s available on virtually every Unix-like system, including minimal installations where less might not be present.

Method 3: Using the getent Command

The getent (get entries) command provides a more sophisticated approach to listing users. It queries databases configured in the Name Service Switch (NSS) configuration file /etc/nsswitch.conf, making it compatible with centralized authentication systems.

To list all users:

getent passwd

The output format matches /etc/passwd, but getent offers significant advantages. It retrieves user information from multiple sources including local files, LDAP directories, NIS servers, and other authentication backends. This makes getent essential in enterprise environments using centralized user management.

Search for a specific user by username:

getent passwd john

Query by User ID (UID):

getent passwd 1001

List users within a UID range:

getent passwd {1000..1010}

To extract only usernames, pipe the output to awk:

getent passwd | awk -F: '{ print $1 }'

The getent command respects your system’s authentication configuration, ensuring you see all users regardless of where their accounts are stored. This makes it the recommended method for modern Linux environments with complex authentication setups.

Method 4: Using the awk Command

The awk programming language excels at text processing and field extraction. For listing users, awk provides flexible filtering and custom output formatting.

To display only usernames:

awk -F':' '{ print $1}' /etc/passwd

The -F':' option sets the colon as the field separator, and { print $1} outputs the first field (username).

Filter regular users with UID greater than 999:

awk -F: '($3>=1000)($3!=65534){ print $1 }' /etc/passwd

This command filters users whose UID (third field) is 1000 or higher while excluding the nobody user (UID 65534).

List system users (UID less than 1000):

awk -F: '($3<1000){ print $1 }' /etc/passwd

Display multiple fields simultaneously:

awk -F: '{print "Username: " $1 "\tUID: " $3 "\tHome: " $6}' /etc/passwd

This creates formatted output showing username, UID, and home directory with labels. You can customize the output to include any combination of fields from the /etc/passwd file.

For better readability with large outputs, pipe awk results to less:

awk -F: '{ print $1, $3, $6}' /etc/passwd | less

Method 5: Using the cut Command

The cut command provides a simpler alternative to awk for basic field extraction. It’s perfect when you need straightforward column selection without complex filtering.

Extract usernames only:

cut -d: -f1 /etc/passwd

The -d: option specifies the colon delimiter, and -f1 selects the first field.

Display usernames and their UIDs:

cut -d: -f1,3 /etc/passwd

Show usernames, UIDs, and home directories:

cut -d: -f1,3,6 /etc/passwd

The cut command works best for simple extraction tasks. When you need conditional filtering or complex formatting, awk becomes more appropriate. Many administrators prefer cut for quick one-liners and shell scripts where simplicity matters more than advanced features.

Method 6: Using the compgen Command

The compgen command is a Bash built-in that completes various shell elements, including user accounts. This method offers a quick way to list users without reading any files.

List all users:

compgen -u

This outputs a simple list of usernames, one per line. The -u option specifically targets user accounts available in the current shell environment.

The compgen command differs from file-based methods because it queries the shell’s internal database. It’s extremely fast since it doesn’t require file I/O operations. However, in some configurations, particularly with network authentication, compgen might not display all users that getent or cat would show.

Use compgen for quick checks in shell scripts or when verifying whether a specific user exists. It’s particularly useful in automation scenarios where speed matters:

if compgen -u | grep -q "^username$"; then
    echo "User exists"
fi

Method 7: Using the lslogins Command

The lslogins utility, part of the util-linux package, provides comprehensive user information with formatted output. This command offers richer metadata than simple /etc/passwd parsing.

Display all users with detailed information:

lslogins

The output includes columns for username, UID, login count, last login time, and more. This formatted table makes it easy to analyze user activity at a glance.

List only regular users (excluding system accounts):

lslogins -u

Show system users only:

lslogins -s

Customize output columns:

lslogins -o USER,UID,LAST-LOGIN

The lslogins command shines in audit scenarios where you need to track user activity. Security teams use it to identify dormant accounts, monitor login patterns, and ensure compliance with access policies. Note that lslogins might not be available on all distributions by default, but you can install it through your package manager if needed.

Method 8: Checking Logged-In and Active Users

Beyond listing all user accounts, administrators often need to monitor currently active sessions. Several commands provide real-time information about logged-in users.

The who Command

Display currently logged-in users:

who

The output shows username, terminal, login time, and IP address for remote connections.

Show all available information:

who -a

This comprehensive view includes boot time, runlevel changes, and idle processes.

The w Command

For detailed user activity information:

w

The w command displays system uptime, load averages, and detailed information about each logged-in user including their current processes, idle time, and CPU usage statistics. The JCPU column shows CPU time used by all processes on the terminal, while PCPU displays time consumed by the current process.

The users Command

Get a simple space-separated list of logged-in usernames:

users

This minimalist output works well in scripts where you only need usernames without additional metadata.

The last Command

View login history:

last

This shows historical login data including successful logins, logout times, and system reboots. Security administrators use last to investigate unauthorized access attempts and audit user behavior.

Check the last login for a specific user:

last username

Method 9: Using GUI Tools

Desktop Linux distributions provide graphical interfaces for user management. While command-line methods offer more power and flexibility, GUI tools suit administrators who prefer visual interfaces.

On GNOME-based systems, access user management through:

  1. Click Activities or press the Super key
  2. Type “Users” in the search box
  3. Click Users under Settings
  4. Authenticate with your password if prompted

The Users interface displays all user accounts with avatars, account types, and login status. You can view account details, modify permissions, and manage passwords through the graphical interface. However, GUI methods have limitations: they require a desktop environment, may not show system users by default, and lack the filtering capabilities of command-line tools.

KDE Plasma users can access similar functionality through System Settings > User Manager. XFCE provides user management through Settings > Users and Groups.

Advanced Filtering and Practical Use Cases

Filtering Users by Groups

Group membership often determines user privileges and access rights. List users belonging to specific groups using these techniques:

Show all members of the sudo group:

getent group sudo | awk -F: '{ print $4 }'

The output displays comma-separated usernames with administrative privileges.

Find all groups a user belongs to:

groups username

Or use the id command for detailed information:

id username

List all users in a specific group with formatted output:

getent group groupname | cut -d: -f4 | tr ',' '\n'

This command extracts the fourth field (group members), then uses tr to convert commas into newlines for better readability.

Practical Scenarios

Security Auditing: Regular user listing helps identify unauthorized accounts. Schedule automated scripts to compare current users against approved baselines:

getent passwd | awk -F: '($3>=1000)($3!=65534){print $1}' > current_users.txt
diff approved_users.txt current_users.txt

Identifying Dormant Accounts: Combine lslogins with date filtering to find inactive accounts that should be disabled:

lslogins -u --time-format=iso --output=USER,LAST-LOGIN

Preparing for Migrations: When moving to new servers, extract complete user information for recreation:

getent passwd | awk -F: '($3>=1000)($3!=65534)' > users_to_migrate.txt

Troubleshooting Permission Issues: Verify user existence and attributes when investigating access problems:

getent passwd problematic_user
id problematic_user

Bulk User Operations: Generate scripts for mass user management:

getent passwd | awk -F: '($3>=1000)($3!=65534){print "usermod -L " $1}' > lock_all_users.sh

Best Practices for Linux User Management

Maintaining proper user account hygiene ensures system security and operational efficiency. Implement these best practices:

Conduct Regular Audits: Schedule monthly reviews of all user accounts. Remove or disable accounts for departed employees immediately. Use lslogins to identify accounts that haven’t logged in recently.

Apply Least Privilege: Users should have only the minimum permissions necessary for their roles. Avoid giving sudo access unless absolutely required. Review group memberships regularly to prevent privilege creep.

Monitor Active Sessions: Use who and w commands to track logged-in users. Investigate unexpected logins, especially outside business hours. Set up automated alerts for suspicious activity.

Document Account Purposes: Maintain a spreadsheet or configuration management database explaining why each system user exists. This prevents accidental deletion of critical service accounts.

Implement Consistent UID/GID Policies: When managing multiple servers, synchronize UIDs across systems to avoid permission conflicts with shared storage. Use centralized authentication (LDAP/Active Directory) for larger environments.

Automate User Listing: Create cron jobs that regularly export user lists and email reports to administrators:

#!/bin/bash
getent passwd | awk -F: '($3>=1000)($3!=65534){print $1, $3}' | mail -s "Daily User Report" admin@example.com

Secure Password Policies: While listing users focuses on accounts rather than passwords, enforce strong password requirements using PAM modules and regular expiration policies.

Backup Authentication Files: Include /etc/passwd, /etc/shadow, and /etc/group in your backup strategy. These files are critical for system recovery.

Troubleshooting Common Issues

Permission Denied Errors

If you receive “Permission denied” when trying to read /etc/passwd, your system has unusual permission settings. Standard configuration makes this file world-readable. Check permissions:

ls -l /etc/passwd

The output should show -rw-r--r-- (644 permissions). If different, restore correct permissions as root:

sudo chmod 644 /etc/passwd

Missing Users in Output

When getent shows different results than cat /etc/passwd, your system uses network authentication. Verify NSS configuration:

cat /etc/nsswitch.conf | grep passwd

Ensure proper sources are configured. For LDAP integration, the line should include passwd: files ldap.

Command Not Found Errors

If lslogins isn’t available, install the util-linux package:

# Debian/Ubuntu
sudo apt install util-linux

# RHEL/CentOS/Fedora
sudo dnf install util-linux

The getent command comes from the glibc-common package, which should be installed by default.

Locked or Disabled Accounts

To identify disabled accounts, check the /etc/shadow file (requires root):

sudo grep '!' /etc/shadow | cut -d: -f1

Accounts with ! or * in the password field are locked and cannot log in.

Corrupted /etc/passwd Files

If the /etc/passwd file becomes corrupted, boot into single-user mode or use a live USB to restore from backup. Always maintain recent backups of authentication files. Verify file integrity:

sudo pwck

This command checks /etc/passwd and /etc/shadow for errors and inconsistencies.

UID Conflicts

When two users share the same UID, permission problems occur. Find duplicate UIDs:

awk -F: '{print $3}' /etc/passwd | sort | uniq -d

Resolve conflicts by assigning unique UIDs using the usermod command:

sudo usermod -u new_uid username

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button