How to List All Users in Linux

Terminal displaying methods to list all Linux users: viewing /etc/passwd, using getent, awk or cut, compgen -u, and sample output rows showing system and regular user accounts sys.

How to List All Users in Linux
SPONSORED

Sponsor message — This article is made possible by Dargslan.com, a publisher of practical, no-fluff IT & developer workbooks.

Why Dargslan.com?

If you prefer doing over endless theory, Dargslan’s titles are built for you. Every workbook focuses on skills you can apply the same day—server hardening, Linux one-liners, PowerShell for admins, Python automation, cloud basics, and more.


How to List All Users in Linux

Managing user accounts stands as one of the fundamental responsibilities for anyone working with Linux systems. Whether you're a system administrator overseeing enterprise servers, a developer configuring development environments, or someone exploring Linux for personal projects, understanding how users are structured and accessed becomes essential knowledge. Every process, file, and system operation in Linux connects to user permissions and ownership, making user management a cornerstone of system security and functionality.

Linux maintains detailed records of all user accounts through specific system files and provides various methods to retrieve this information. A user account in Linux represents more than just a login credential—it encompasses permissions, group memberships, home directories, default shells, and security parameters that determine what actions can be performed on the system. These accounts can belong to actual people, system services, or applications that require specific privileges to function properly.

Throughout this comprehensive guide, you'll discover multiple approaches to listing and examining user accounts on Linux systems. We'll explore the underlying file structures where user information resides, examine command-line tools that extract and display user data, and investigate advanced techniques for filtering and analyzing user accounts. You'll learn to distinguish between regular users and system accounts, understand the significance of user IDs, and gain practical knowledge applicable to real-world system administration scenarios.

Understanding Linux User Account Structure

Linux systems organize user information through a hierarchical structure that separates authentication data from descriptive account information. The operating system relies on several configuration files working in concert to maintain comprehensive user records. This separation serves both security and functional purposes, allowing different system components to access only the information they require while protecting sensitive data like password hashes.

The primary file containing user account information is /etc/passwd, which stores fundamental details about every user account on the system. Despite its name suggesting password storage, modern Linux systems have moved actual password data to a separate, more secure location. The passwd file remains world-readable because many system utilities need to map user IDs to usernames, check default shells, or locate home directories without requiring elevated privileges.

The passwd File Format

Each line in the /etc/passwd file represents a single user account and contains seven fields separated by colons. Understanding this format proves crucial for anyone working with user management, as numerous commands and scripts parse this file to extract user information. The structure maintains backward compatibility with early Unix systems while accommodating modern security requirements.

Field Position Field Name Description Example Value
1 Username The login name used to access the system john
2 Password Placeholder Usually 'x' indicating shadow passwords x
3 User ID (UID) Numeric identifier for the user 1000
4 Group ID (GID) Primary group numeric identifier 1000
5 GECOS Field User information like full name John Smith
6 Home Directory Path to user's home directory /home/john
7 Login Shell Default shell program /bin/bash
Understanding the passwd file structure transforms user management from mysterious commands into logical operations. Every user-related action ultimately references these seven fields, making them the foundation of Linux identity management.

System Users versus Regular Users

Linux distributions create numerous user accounts beyond those belonging to actual people. System accounts exist to run services, daemons, and background processes with limited privileges, following the principle of least privilege. These accounts typically cannot log in interactively and serve purely functional purposes. Distinguishing between system and regular users becomes important when auditing accounts or performing administrative tasks.

The differentiation between user types typically relies on User ID ranges. Most Linux distributions reserve UIDs below 1000 for system accounts, while regular user accounts begin at 1000 or higher. However, this convention varies between distributions, with some using 500 as the threshold. The root user always maintains UID 0, representing the superuser with unrestricted system access.

Basic Methods to Display All Users

Several straightforward approaches exist for viewing user accounts on Linux systems. These methods range from directly examining system files to using specialized commands designed for user information retrieval. Each approach offers different advantages depending on your specific needs and the level of detail required.

Viewing the passwd File Directly

The most direct method involves displaying the contents of /etc/passwd using standard file viewing commands. This approach provides complete visibility into all user accounts without filtering or processing. You can use various commands to accomplish this task:

cat /etc/passwd

This command outputs every line in the passwd file, showing all seven fields for each user. While comprehensive, the output can be overwhelming on systems with many accounts. For more controlled viewing, especially on systems with numerous users, you might prefer using pagination:

less /etc/passwd

The less command allows scrolling through the file one screen at a time, searching for specific entries, and navigating backward through the content. This proves particularly useful when examining systems with dozens or hundreds of user accounts.

Extracting Just Usernames

Often you only need a list of usernames without the additional fields. The cut command excels at extracting specific fields from delimited text files. Since the passwd file uses colons as field separators, extracting usernames becomes straightforward:

cut -d: -f1 /etc/passwd

This command instructs cut to use the colon as a delimiter (-d:) and extract the first field (-f1), which contains the username. The output provides a clean list of every username on the system, one per line. This format works well for further processing through scripts or for quick visual inspection.

For alphabetically sorted output, you can pipe the results through the sort command:

cut -d: -f1 /etc/passwd | sort
Simplicity often proves more powerful than complexity. A single line combining cut and sort provides immediate, readable results that answer the most common question: who has accounts on this system?

Using getent Command

The getent command offers a more sophisticated approach to retrieving user information. Unlike directly reading /etc/passwd, getent queries the system's Name Service Switch (NSS) configuration, which means it returns users from all configured sources including local files, LDAP directories, NIS, and other authentication backends.

getent passwd

This command displays user information in the same format as /etc/passwd, but includes users from networked directory services if configured. This makes getent the preferred method in enterprise environments where user accounts might be centrally managed through directory services rather than stored locally.

To retrieve information about a specific user:

getent passwd username

The getent approach proves particularly valuable in heterogeneous environments where user databases span multiple systems and authentication mechanisms. It provides a unified view regardless of where account information actually resides.

Advanced Filtering and User Analysis

Beyond simple listing, administrators frequently need to filter users based on specific criteria, analyze account properties, or identify accounts meeting certain conditions. Linux command-line tools provide powerful capabilities for such analysis through text processing utilities and scripting.

Filtering Regular Users from System Accounts

Separating human users from system service accounts helps focus administrative attention on accounts that might require password policies, access reviews, or other security measures. The most reliable method examines User ID ranges:

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

This awk command sets the field separator to colon (-F:), checks if the third field (UID) is 1000 or greater, and prints the first field (username) for matching records. The result shows only regular user accounts, excluding system accounts with lower UIDs.

For distributions using different UID thresholds, adjust the comparison value accordingly. Some administrators prefer including the UID in the output for verification:

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

Identifying Users with Login Shells

Not all accounts can log in interactively. Many system accounts use /sbin/nologin or /bin/false as their shell, preventing interactive access. Filtering for accounts with legitimate login shells helps identify which accounts could potentially access the system:

grep -v 'nologin\|false' /etc/passwd | cut -d: -f1

This command uses grep to exclude (-v) lines containing either "nologin" or "false", then extracts usernames from the remaining entries. The result shows users who could potentially log in, though it doesn't indicate whether the accounts are currently active or locked.

  • 🔍 Examining shell assignments reveals which accounts are intended for interactive use versus service operation
  • 🔐 Accounts with /bin/bash or /bin/sh shells typically belong to administrators or developers
  • ⚙️ Service accounts often use /usr/sbin/nologin to prevent unauthorized interactive access
  • 🎯 Regular users might have shells like /bin/zsh, /bin/fish, or other alternatives based on preference
  • 🚫 The /bin/false shell immediately exits, making it suitable for accounts that should never have shell access

Displaying Users with Home Directories

Examining home directory assignments helps identify user accounts that maintain personal file spaces. This information proves useful when auditing disk usage, planning backups, or investigating account activity:

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

This command displays each username alongside its home directory. You can further filter for specific directory patterns:

awk -F: '$6 ~ /^\/home\// {print $1, $6}' /etc/passwd

This variation shows only users whose home directories reside under /home, typically indicating regular user accounts rather than system accounts which often use directories like /var/lib or /usr/sbin.

Home directory analysis reveals usage patterns and helps identify orphaned directories where user accounts have been deleted but their files remain, consuming storage and potentially containing sensitive data.

Programmatic User Enumeration

Scripting languages provide structured approaches to user enumeration, offering greater control over output formatting and enabling complex analysis. Both shell scripts and higher-level languages can parse user information efficiently.

Shell Script Approach

A well-structured shell script can present user information in customized formats while performing validation and filtering. Here's a comprehensive example:

#!/bin/bash

echo "Regular User Accounts on $(hostname)"
echo "======================================"
echo ""

while IFS=: read -r username password uid gid gecos home shell; do
    if [ "$uid" -ge 1000 ] && [ "$uid" -ne 65534 ]; then
        printf "%-15s UID: %-6s Shell: %-20s\n" "$username" "$uid" "$shell"
    fi
done < /etc/passwd

This script reads the passwd file line by line, splits each line into variables based on the colon delimiter, and formats output for regular users. The condition excludes the "nobody" account (UID 65534) which, despite having a high UID, serves as a system account.

Using Python for Advanced Analysis

Python's pwd module provides object-oriented access to user database information, enabling sophisticated analysis:

#!/usr/bin/env python3
import pwd

print("User Accounts Analysis")
print("=" * 50)

regular_users = []
system_users = []

for user in pwd.getpwall():
    if user.pw_uid >= 1000 and user.pw_uid != 65534:
        regular_users.append(user)
    else:
        system_users.append(user)

print(f"\nRegular Users: {len(regular_users)}")
for user in sorted(regular_users, key=lambda x: x.pw_name):
    print(f"  {user.pw_name:15} (UID: {user.pw_uid})")

print(f"\nSystem Accounts: {len(system_users)}")
print(f"Total Accounts: {len(regular_users) + len(system_users)}")

This Python script categorizes users, counts them by type, and presents organized output. The pwd module handles parsing automatically, reducing error potential compared to manual text processing.

Examining Currently Logged-In Users

Listing all defined user accounts differs from identifying who is currently using the system. Several commands reveal active user sessions, providing real-time visibility into system access.

The who Command

The who command displays information about currently logged-in users:

who

Output typically includes username, terminal device, login time, and remote host for network connections. For more detailed information including idle time:

who -u

This variation adds idle time indicators, helping identify inactive sessions that might be candidates for termination or investigation.

The w Command for Detailed Session Information

The w command provides comprehensive information about logged-in users and their activities:

w

This command displays not only who is logged in but also system load averages, how long each user has been logged in, idle time, and what command each user is currently executing. This information proves invaluable for system monitoring and troubleshooting.

Active session monitoring complements user account enumeration by revealing not just who could access the system, but who actually is accessing it and what they're doing.

The users Command for Simple Lists

For a concise list of logged-in usernames without additional details:

users

This command outputs a space-separated list of currently logged-in users. If a user has multiple sessions, their name appears multiple times. This simple format works well for scripting or quick checks.

Security Considerations and Best Practices

Understanding user enumeration techniques carries security implications. While legitimate administrators need these capabilities for system management, the same information can aid attackers in reconnaissance. Balancing operational needs with security requires thoughtful policies and monitoring.

Protecting User Information

Although /etc/passwd must be world-readable for system functionality, limiting access to other user-related files enhances security. The /etc/shadow file, containing password hashes, should maintain strict permissions:

ls -l /etc/shadow

Proper permissions show -rw------- with root ownership, preventing non-privileged users from reading password hashes. Regular audits should verify these permissions remain intact.

Monitoring for Unauthorized Accounts

Regular user account audits help detect unauthorized additions. Establishing a baseline of legitimate accounts and periodically comparing current accounts against this baseline reveals suspicious changes:

cut -d: -f1 /etc/passwd | sort > current_users.txt
diff baseline_users.txt current_users.txt

This approach highlights additions or removals since the baseline was created. Automating such comparisons through scheduled scripts provides ongoing monitoring without manual intervention.

Security Practice Implementation Method Benefit
Regular Account Audits Scheduled scripts comparing user lists Detects unauthorized account creation
UID Range Enforcement Policy requiring regular users above 1000 Prevents confusion with system accounts
Disabled Account Tracking Monitor shadow file for locked accounts Identifies accounts that should be removed
Shell Restriction Limit available shells in /etc/shells Reduces attack surface for compromised accounts
Home Directory Permissions Enforce 700 or 750 permissions Prevents unauthorized access to user files

Identifying Inactive or Stale Accounts

Accounts that remain defined but unused represent security risks. These orphaned accounts might have weak passwords, outdated security settings, or serve as targets for attackers seeking to establish persistence. Identifying such accounts requires examining login history:

lastlog | grep -v "Never"

The lastlog command displays the most recent login time for each user. Filtering out users who have never logged in helps focus on accounts that were once active but have become dormant. Establishing policies for disabling or removing inactive accounts after defined periods reduces the attack surface.

Every unnecessary user account represents a potential security vulnerability. Regular audits and aggressive removal of unused accounts should form core components of system security practices.

Troubleshooting Common Issues

Working with user enumeration occasionally encounters complications stemming from system configuration, file corruption, or permission issues. Understanding common problems and their solutions helps maintain smooth operations.

Inconsistent User Information

When user information appears different across various commands, the cause often involves Name Service Switch configuration. The /etc/nsswitch.conf file determines which sources the system consults for user information and in what order:

grep passwd /etc/nsswitch.conf

The output shows configured sources like "files" (local /etc/passwd), "ldap" (directory services), or "systemd" (systemd-homed). If getent shows different users than directly reading /etc/passwd, additional sources are providing user data. Understanding your NSS configuration explains these discrepancies.

Permission Denied Errors

While /etc/passwd should be world-readable, other user-related files require elevated privileges. If commands fail with permission errors, verify you're using appropriate privileges for the operation. Some user information, particularly from /etc/shadow, requires root access:

sudo getent shadow username

Always use the minimum necessary privileges. If you only need information from passwd, don't unnecessarily escalate to root access.

Corrupted User Database

Rare but serious, corruption in /etc/passwd can prevent system login or cause authentication failures. Symptoms include syntax errors when parsing the file or users unable to log in. Validation tools can check file integrity:

pwck

The pwck command verifies the passwd and shadow files for consistency, checking field counts, valid characters, and cross-references between files. Running this command periodically or after manual edits helps catch corruption early.

Backup copies of /etc/passwd and /etc/shadow should exist on every system, preferably in secure locations. These backups become critical when recovering from corruption or accidental deletion.

Integration with System Administration Tasks

User enumeration rarely exists in isolation—it typically supports broader administrative objectives. Understanding how to incorporate user listing into common workflows enhances efficiency and effectiveness.

Bulk User Operations

When performing actions across multiple users, generating user lists programmatically ensures completeness and accuracy. For example, resetting permissions on all user home directories:

for user in $(awk -F: '$3 >= 1000 {print $1}' /etc/passwd); do
    if [ -d "/home/$user" ]; then
        echo "Processing /home/$user"
        # chmod or chown commands here
    fi
done

This pattern—enumerate users, filter appropriately, perform action—applies to numerous administrative tasks from backup operations to security audits.

Reporting and Documentation

Generating formatted reports about user accounts supports compliance requirements, audits, and documentation needs. Combining user enumeration with formatting tools produces professional output:

#!/bin/bash

echo "User Account Report - $(date)"
echo "System: $(hostname)"
echo ""
echo "Regular User Accounts"
echo "====================="

awk -F: '$3 >= 1000 && $3 != 65534 {
    printf "%-15s UID: %-6s Home: %-25s Shell: %s\n", $1, $3, $6, $7
}' /etc/passwd | sort

echo ""
echo "Total Regular Users: $(awk -F: '$3 >= 1000 && $3 != 65534' /etc/passwd | wc -l)"

Such scripts can be scheduled to run periodically, automatically generating documentation that tracks user account changes over time.

Integration with Configuration Management

Modern infrastructure automation tools like Ansible, Puppet, or Chef often need to enumerate existing users before applying configuration changes. These tools typically provide their own user management modules, but understanding underlying Linux mechanisms helps troubleshoot issues and customize behavior.

Ansible, for example, can gather user information as facts:

- name: Get all users
  shell: "cut -d: -f1 /etc/passwd"
  register: system_users

- name: Display user count
  debug:
    msg: "System has {{ system_users.stdout_lines | length }} user accounts"

Understanding native Linux user enumeration methods enables creating more efficient and reliable automation scripts.

Alternative User Management Systems

Traditional /etc/passwd-based user management, while still prevalent, coexists with modern alternatives designed for specific use cases. Awareness of these systems helps when encountering unfamiliar configurations.

Systemd-homed

Systemd-homed provides portable home directories with integrated encryption and user management. Users managed by systemd-homed appear in standard user listings but maintain additional metadata:

homectl list

This command shows users managed by systemd-homed specifically. These users integrate with traditional mechanisms, appearing in getent output, but offer enhanced features like automatic home directory mounting and encryption.

LDAP and Active Directory Integration

Enterprise environments often centralize user management through directory services. When Linux systems authenticate against LDAP or Active Directory, local user listings may show only system accounts, with regular users existing in the directory:

getent passwd | wc -l  # Shows all users including directory
cut -d: -f1 /etc/passwd | wc -l  # Shows only local users

The difference between these counts indicates users sourced from network directories. Tools like ldapsearch or adcli query directory services directly for comprehensive user information.

Container and Virtualization Considerations

Containerized environments introduce complexity to user enumeration. Users inside containers exist independently from host system users, though UID mapping can create relationships between them. When managing containerized systems, distinguish between host users and container users:

# Host users
getent passwd

# Container users (example with Docker)
docker exec container_name getent passwd

Understanding these boundaries prevents confusion when troubleshooting permission issues or conducting security audits across containerized infrastructure.

Modern Linux environments increasingly blend traditional local user management with networked directory services, containerization, and advanced features like systemd-homed. Effective administration requires understanding all these layers and how they interact.

Practical Examples and Real-World Scenarios

Applying user enumeration techniques to concrete scenarios demonstrates their practical value and reinforces conceptual understanding. These examples represent common administrative tasks encountered in production environments.

Security Audit Scenario

Imagine conducting a security audit requiring identification of all accounts with root privileges or sudo access. This involves multiple steps combining user enumeration with permission analysis:

# Find users with UID 0 (root equivalent)
awk -F: '$3 == 0 {print $1}' /etc/passwd

# Find users in sudo or wheel groups
getent group sudo | cut -d: -f4
getent group wheel | cut -d: -f4

# Check sudoers file for additional grants
grep -v '^#' /etc/sudoers | grep -v '^$'

Combining these outputs provides comprehensive visibility into privileged access, essential for security assessments and compliance audits.

User Migration Planning

When migrating users to a new system, generating comprehensive user lists with all relevant attributes facilitates planning and execution:

#!/bin/bash

echo "User Migration Data Export"
echo "==========================="

awk -F: '$3 >= 1000 && $3 != 65534 {
    print "Username:", $1
    print "UID:", $3
    print "GID:", $4
    print "Home:", $6
    print "Shell:", $7
    print "---"
}' /etc/passwd

This information guides recreation of user accounts on the target system, ensuring UID/GID consistency that preserves file ownership relationships.

Disk Usage Analysis

Identifying which users consume the most disk space requires combining user enumeration with disk usage tools:

#!/bin/bash

echo "Home Directory Disk Usage"
echo "========================="

for user in $(awk -F: '$3 >= 1000 && $6 ~ /^\/home/ {print $1}' /etc/passwd); do
    if [ -d "/home/$user" ]; then
        size=$(du -sh "/home/$user" 2>/dev/null | cut -f1)
        printf "%-15s %s\n" "$user" "$size"
    fi
done | sort -k2 -h -r

This script enumerates users with home directories under /home, calculates space usage, and sorts by size in descending order, quickly revealing the largest consumers of storage.

Note: When running disk usage analysis, consider excluding mounted network filesystems or external storage that might skew results. Use the -x flag with du to stay within the same filesystem.

Documentation and Compliance Requirements

Many regulatory frameworks and security standards mandate regular user account reviews and documentation. Understanding how to generate compliant reports from user enumeration data satisfies these requirements while supporting good security practices.

Creating Audit Trail Documentation

Maintaining historical records of user accounts helps track changes over time and provides evidence of due diligence during audits. Automated scripts can generate timestamped snapshots:

#!/bin/bash

AUDIT_DIR="/var/log/user_audits"
mkdir -p "$AUDIT_DIR"

TIMESTAMP=$(date +%Y%m%d_%H%M%S)
AUDIT_FILE="$AUDIT_DIR/user_audit_$TIMESTAMP.txt"

{
    echo "User Account Audit"
    echo "Generated: $(date)"
    echo "System: $(hostname)"
    echo ""
    echo "All User Accounts:"
    echo "=================="
    getent passwd | sort
    echo ""
    echo "Regular Users (UID >= 1000):"
    echo "============================"
    awk -F: '$3 >= 1000 {print $1, $3, $6, $7}' /etc/passwd | sort
} > "$AUDIT_FILE"

echo "Audit saved to $AUDIT_FILE"

Running this script monthly or quarterly creates a historical record demonstrating ongoing account management and oversight.

Compliance Reporting Formats

Different compliance frameworks require specific information formats. Adapting user enumeration output to these formats streamlines compliance processes. For example, generating CSV output suitable for spreadsheet import:

#!/bin/bash

echo "Username,UID,GID,Home Directory,Shell,Last Login"

while IFS=: read -r username x uid gid gecos home shell; do
    if [ "$uid" -ge 1000 ] && [ "$uid" -ne 65534 ]; then
        last_login=$(lastlog -u "$username" | tail -1 | awk '{print $4, $5, $6, $9}')
        echo "$username,$uid,$gid,$home,$shell,$last_login"
    fi
done < /etc/passwd

This script produces comma-separated values easily imported into compliance tracking systems or analyzed in spreadsheet applications.

Performance Considerations

While user enumeration typically completes quickly on systems with dozens or hundreds of accounts, performance becomes relevant in large enterprise environments with thousands of users, especially when accounts are sourced from network directories.

Optimizing Large-Scale Enumeration

When working with extensive user databases, consider performance implications of different approaches. Reading local files proves faster than querying network directories, but may not reflect the complete user population. Caching strategies can balance completeness with performance:

#!/bin/bash

CACHE_FILE="/tmp/user_cache.txt"
CACHE_AGE=3600  # 1 hour in seconds

if [ -f "$CACHE_FILE" ]; then
    CACHE_TIME=$(stat -c %Y "$CACHE_FILE")
    CURRENT_TIME=$(date +%s)
    AGE=$((CURRENT_TIME - CACHE_TIME))
    
    if [ $AGE -lt $CACHE_AGE ]; then
        cat "$CACHE_FILE"
        exit 0
    fi
fi

getent passwd | tee "$CACHE_FILE"

This caching approach queries the full user database only when the cache expires, dramatically improving performance for frequently-run scripts.

Minimizing Network Directory Impact

When user information comes from network directories, enumeration operations generate network traffic and directory server load. Limiting queries to necessary information reduces impact:

# Instead of full enumeration
getent passwd

# Query specific users when possible
for user in alice bob charlie; do
    getent passwd "$user"
done

This targeted approach proves more efficient when you need information about specific users rather than the entire population.

Frequently Asked Questions

How can I count the total number of users on a Linux system?

Counting users depends on whether you want all accounts or only regular users. For all accounts, use getent passwd | wc -l which counts lines in the complete user database including network sources. For only regular users (UID >= 1000), use awk -F: '$3 >= 1000 && $3 != 65534' /etc/passwd | wc -l which filters by UID range and excludes the nobody account. The difference between these counts reveals how many system accounts exist versus regular user accounts.

What's the difference between /etc/passwd and /etc/shadow?

The /etc/passwd file contains basic user account information like username, UID, home directory, and shell. It must be world-readable because many system utilities need this information. The /etc/shadow file contains security-sensitive data including encrypted passwords, password aging information, and account expiration dates. Shadow is readable only by root to protect password hashes from unauthorized access. This separation allows necessary account information to be public while keeping authentication credentials secure.

Can I list users who are currently logged into the system?

Yes, several commands show currently logged-in users. The who command displays basic information about active sessions including username, terminal, and login time. The w command provides more detail including what each user is currently doing and how long they've been idle. The users command gives a simple space-separated list of logged-in usernames. For the most comprehensive view including remote connections, use w -i which shows IP addresses instead of hostnames.

How do I find users with specific shells like /bin/bash?

You can filter users by their assigned shell using grep or awk. The command grep '/bin/bash$' /etc/passwd | cut -d: -f1 finds all users with bash as their shell by searching for lines ending in /bin/bash and extracting the username field. Alternatively, awk -F: '$7 == "/bin/bash" {print $1}' /etc/passwd accomplishes the same task using awk's field matching. These approaches help identify interactive users versus service accounts that typically use /sbin/nologin or /bin/false.

Why do some users appear in getent passwd but not in /etc/passwd?

This occurs when your system uses network-based authentication like LDAP, Active Directory, or NIS. The getent command queries all sources configured in /etc/nsswitch.conf, including network directories, while directly reading /etc/passwd shows only locally defined accounts. In enterprise environments, most regular users exist in centralized directories while only system accounts and perhaps a few administrative users are defined locally. Check /etc/nsswitch.conf to see which sources your system consults for user information.

How can I identify inactive or unused user accounts?

The lastlog command shows the most recent login for each user. Accounts showing "Never logged in" or with very old last login dates may be candidates for removal. Use lastlog | grep -v "Never" to see only accounts that have been used at least once. For more sophisticated analysis, combine this with account creation dates from chage -l username to identify accounts created but never used. Always verify with account owners before removing accounts, as some legitimate accounts like service accounts may never show interactive logins.

What permissions should /etc/passwd and /etc/shadow have?

The /etc/passwd file should have permissions -rw-r--r-- (644) making it readable by all users but writable only by root. This allows system utilities to read user information without elevated privileges. The /etc/shadow file must have permissions -rw------- (600) or sometimes -rw-r----- (640) with shadow group ownership, restricting access to root only or root plus the shadow group. Incorrect permissions on shadow could expose password hashes to unauthorized users, representing a serious security vulnerability. Verify these permissions regularly using ls -l /etc/passwd /etc/shadow.

Can I list users belonging to a specific group?

Yes, you can identify group members using the getent command. Use getent group groupname to see information about a specific group including its members listed in the fourth field. For cleaner output showing only usernames, use getent group groupname | cut -d: -f4 | tr ',' '\n' which extracts the member list and places each username on a separate line. Remember that this shows only users explicitly listed in the group file—users whose primary group is the target group appear differently and require additional queries.