How to list logged-in users → who
How to List Logged-in Users → who
Table of Contents
1. [Introduction](#introduction)
2. [Prerequisites](#prerequisites)
3. [Understanding the who Command](#understanding-the-who-command)
4. [Basic Usage](#basic-usage)
5. [Command Options and Flags](#command-options-and-flags)
6. [Practical Examples](#practical-examples)
7. [Output Format Explained](#output-format-explained)
8. [Advanced Usage Scenarios](#advanced-usage-scenarios)
9. [Related Commands](#related-commands)
10. [Troubleshooting Common Issues](#troubleshooting-common-issues)
11. [Best Practices](#best-practices)
12. [Security Considerations](#security-considerations)
13. [Conclusion](#conclusion)
Introduction
The `who` command is a fundamental Unix/Linux utility that displays information about users currently logged into the system. Whether you're a system administrator monitoring user activity, a developer debugging session issues, or simply curious about who else is using a shared system, the `who` command provides essential insights into active user sessions.
This comprehensive guide will teach you everything you need to know about using the `who` command effectively, from basic usage to advanced scenarios. You'll learn how to interpret the output, use various command options, troubleshoot common issues, and implement best practices for system monitoring and security.
Prerequisites
Before diving into the `who` command, ensure you have:
- Operating System: Linux, Unix, macOS, or Unix-like system
- Access Level: Basic user privileges (no root access required for most operations)
- Terminal Access: Command line interface or SSH access to the target system
- Basic Knowledge: Familiarity with command line operations
- Optional: Understanding of user management concepts in Unix/Linux systems
Understanding the who Command
What is the who Command?
The `who` command reads information from the system's utmp file (usually located at `/var/run/utmp` or `/etc/utmp`) to display details about currently logged-in users. This file maintains records of user login sessions, terminal information, and timestamps.
Key Information Provided
The `who` command typically displays:
- Username: The login name of the user
- Terminal: The terminal or connection type (tty, pts, console)
- Login Time: When the user logged in
- Remote Host: For remote connections, the source IP or hostname
- Process ID: In some cases, the process ID of the user's session
Basic Usage
Simple who Command
The most basic usage of the `who` command requires no additional parameters:
```bash
who
```
Example Output:
```
john tty1 2024-01-15 09:30
alice pts/0 2024-01-15 10:15 (192.168.1.100)
bob pts/1 2024-01-15 11:22 (office.company.com)
```
Understanding Basic Output
Each line in the output represents one logged-in user session:
- john tty1: User "john" is logged in via terminal tty1 (physical console)
- alice pts/0: User "alice" is connected via pseudo-terminal 0 (likely SSH)
- bob pts/1: User "bob" is connected via pseudo-terminal 1 from a remote host
Command Options and Flags
Essential Options
-H, --heading
Displays column headers for better readability:
```bash
who -H
```
Output:
```
NAME LINE TIME COMMENT
john tty1 2024-01-15 09:30
alice pts/0 2024-01-15 10:15 (192.168.1.100)
```
-u, --users
Shows idle time and process ID for each user:
```bash
who -u
```
Output:
```
john tty1 2024-01-15 09:30 . 1234
alice pts/0 2024-01-15 10:15 00:05 5678 (192.168.1.100)
```
The idle time shows how long the terminal has been inactive:
- `.` indicates activity within the last minute
- `old` indicates idle for more than 24 hours
- Time format shows hours:minutes for recent activity
-b, --boot
Displays the last system boot time:
```bash
who -b
```
Output:
```
system boot 2024-01-15 08:00
```
-r, --runlevel
Shows the current run level:
```bash
who -r
```
Output:
```
run-level 5 2024-01-15 08:01
```
-q, --count
Provides a quick count of logged-in users:
```bash
who -q
```
Output:
```
john alice bob
users = 3
```
Advanced Options
-a, --all
Equivalent to using `-b -d --login -p -r -t -T -u` options together:
```bash
who -a
```
This comprehensive output includes:
- Boot time
- Dead processes
- Login processes
- Active processes
- Run level
- Time changes
- Terminal writability
- User information with idle times
-d, --dead
Shows dead processes (terminated but not yet cleaned up):
```bash
who -d
```
-l, --login
Displays system login processes:
```bash
who -l
```
-p, --process
Shows active processes spawned by init:
```bash
who -p
```
-t, --time
Shows last system clock change:
```bash
who -t
```
-T, -w, --mesg
Adds a column showing message status (+ for writable, - for not writable):
```bash
who -T
```
Output:
```
john + tty1 2024-01-15 09:30
alice - pts/0 2024-01-15 10:15 (192.168.1.100)
```
Practical Examples
Example 1: Monitoring System Activity
System administrators often need to monitor who is currently using the system:
```bash
Get detailed user information with headers
who -Hu
Check system uptime and users
who -b && echo "Current users:" && who -q
```
Example 2: Security Monitoring
For security purposes, you might want to check for unusual login activity:
```bash
Show all user sessions with remote hosts
who -H | grep -E "(pts|ssh)"
Monitor for multiple sessions from same user
who | sort | uniq -c -f1
```
Example 3: Terminal Session Management
When managing multiple terminal sessions:
```bash
Show your own session information
who am i
Show all sessions with writability status
who -T
Find idle sessions
who -u | awk '$4 != "." {print $1, $2, "idle:", $4}'
```
Example 4: Automated Monitoring Script
Here's a practical bash script for monitoring user sessions:
```bash
#!/bin/bash
user_monitor.sh
echo "=== System Login Report ==="
echo "Generated on: $(date)"
echo
echo "System Boot Time:"
who -b
echo
echo "Current Run Level:"
who -r
echo
echo "Logged-in Users (with idle time):"
who -Hu
echo
echo "User Count Summary:"
who -q
echo
Alert for multiple sessions
echo "Users with Multiple Sessions:"
who | awk '{print $1}' | sort | uniq -c | awk '$1 > 1 {print $2, "has", $1, "sessions"}'
```
Output Format Explained
Standard Output Fields
1. USERNAME: The login name of the user
2. TERMINAL: The terminal device name
- `tty1`, `tty2`, etc.: Physical console terminals
- `pts/0`, `pts/1`, etc.: Pseudo-terminals (SSH, remote sessions)
- `console`: System console
3. LOGIN_TIME: Date and time when the user logged in
4. REMOTE_HOST: For network connections, shows the source host (in parentheses)
Extended Output Fields (with -u option)
5. IDLE_TIME: How long the terminal has been inactive
6. PID: Process ID of the user's login shell
Message Status (with -T option)
- `+`: Terminal accepts messages (write, wall, talk commands work)
- `-`: Terminal blocks messages
- `?`: Cannot determine message status
Advanced Usage Scenarios
Combining who with Other Commands
Finding Specific Users
```bash
Check if a specific user is logged in
who | grep "username"
Count sessions for a specific user
who | grep -c "username"
```
Monitoring Remote Connections
```bash
Show only remote connections
who | grep "("
List unique remote hosts
who | grep -o '([^)]*)' | sort | uniq
```
System Health Checks
```bash
Check for old idle sessions
who -u | awk '$4 == "old" {print "Old session:", $1, $2}'
Monitor system load vs. user count
echo "Users: $(who -q | tail -1)" && uptime
```
Integration with System Monitoring
Log Analysis
```bash
Create a log entry for current users
echo "$(date): $(who -q | tail -1)" >> /var/log/user_sessions.log
Compare current users with previous snapshot
diff <(cat /tmp/previous_users) <(who | sort) && who | sort > /tmp/previous_users
```
Automated Alerts
```bash
Alert if too many users are logged in
USER_COUNT=$(who -q | tail -1 | awk '{print $3}')
if [ $USER_COUNT -gt 10 ]; then
echo "Warning: $USER_COUNT users logged in" | mail -s "High User Count" admin@company.com
fi
```
Related Commands
w Command
Provides more detailed information including what users are doing:
```bash
w
```
Output includes:
- Load averages
- Current processes for each user
- CPU and memory usage
users Command
Simple list of logged-in usernames:
```bash
users
```
last Command
Shows login history:
```bash
last
last -n 10 # Show last 10 logins
```
finger Command
Detailed user information (if available):
```bash
finger username
```
ps Command
Show processes for specific users:
```bash
ps -u username
```
Troubleshooting Common Issues
Issue 1: who Command Not Found
Problem: `bash: who: command not found`
Solution:
```bash
Check if who is installed
which who
On some minimal systems, install coreutils
Ubuntu/Debian:
sudo apt-get install coreutils
CentOS/RHEL:
sudo yum install coreutils
```
Issue 2: Empty Output
Problem: `who` command returns no output despite users being logged in
Possible Causes and Solutions:
1. Corrupted utmp file:
```bash
Check utmp file
ls -la /var/run/utmp /var/log/utmp /etc/utmp
Restart system logging (as root)
sudo systemctl restart systemd-logind
```
2. Permission issues:
```bash
Check file permissions
ls -la /var/run/utmp
Should be readable by all users
```
Issue 3: Incorrect Time Display
Problem: Login times appear incorrect
Solution:
```bash
Check system time
date
Check timezone
timedatectl
Synchronize time (as root)
sudo ntpdate -s time.nist.gov
```
Issue 4: Missing Remote Host Information
Problem: Remote connections don't show source host
Solution:
```bash
Check if reverse DNS is working
nslookup [IP_ADDRESS]
For SSH, ensure proper logging is enabled in /etc/ssh/sshd_config:
LogLevel INFO
```
Issue 5: Inconsistent Output Format
Problem: Output format varies between systems
Solution:
```bash
Use standardized options for consistent output
who -H # Always include headers
For scripting, use specific field extraction
who | awk '{print $1, $2, $3, $4}'
```
Best Practices
1. Regular Monitoring
Implement regular user session monitoring:
```bash
Add to crontab for hourly checks
0 /usr/bin/who -q | tail -1 >> /var/log/hourly_user_count.log
```
2. Security Auditing
Use `who` as part of security monitoring:
```bash
Daily security check script
#!/bin/bash
echo "Daily Security Report - $(date)" > /tmp/security_report.txt
echo "Active Users:" >> /tmp/security_report.txt
who -H >> /tmp/security_report.txt
echo "" >> /tmp/security_report.txt
echo "Remote Connections:" >> /tmp/security_report.txt
who | grep "(" >> /tmp/security_report.txt
```
3. Performance Considerations
For systems with many users:
```bash
Use -q for quick counts instead of full output
who -q | tail -1
Combine with other commands efficiently
who | wc -l # Count users without full output
```
4. Documentation and Logging
Maintain proper documentation:
```bash
Create comprehensive system status
{
echo "System Status Report"
echo "==================="
echo "Generated: $(date)"
echo
echo "System Boot Time:"
who -b
echo
echo "Current Users:"
who -H
echo
echo "System Load:"
uptime
} > system_status.txt
```
5. Error Handling in Scripts
Always include error handling:
```bash
#!/bin/bash
Robust user checking script
if ! command -v who &> /dev/null; then
echo "Error: 'who' command not found"
exit 1
fi
USER_INFO=$(who 2>/dev/null)
if [ $? -ne 0 ]; then
echo "Error: Unable to retrieve user information"
exit 1
fi
echo "$USER_INFO"
```
Security Considerations
1. Information Disclosure
The `who` command reveals:
- Active usernames
- Connection sources
- Login times
- Session activity levels
Mitigation:
- Limit access to user information on sensitive systems
- Monitor for unauthorized information gathering
- Use proper file permissions on utmp files
2. Session Monitoring
For security monitoring:
```bash
Detect unusual login patterns
who | awk '{print $1}' | sort | uniq -c | sort -nr
Monitor for concurrent sessions
who | awk '{print $1, $2}' | sort
```
3. Intrusion Detection
Integrate `who` into intrusion detection:
```bash
Alert on new user sessions
CURRENT_USERS=$(who | wc -l)
if [ $CURRENT_USERS -gt $EXPECTED_MAX_USERS ]; then
logger "WARNING: Unusual number of user sessions: $CURRENT_USERS"
fi
```
4. Privacy Considerations
Be aware of privacy implications:
- User activity monitoring policies
- Data retention requirements
- Access logging compliance
Conclusion
The `who` command is an essential tool for system administration, security monitoring, and user session management. This comprehensive guide has covered everything from basic usage to advanced scenarios, providing you with the knowledge to effectively monitor and manage user sessions on Unix/Linux systems.
Key Takeaways
1. Basic Usage: Use `who` for quick user session overview
2. Advanced Options: Leverage flags like `-H`, `-u`, and `-a` for detailed information
3. Security Monitoring: Integrate `who` into security workflows for intrusion detection
4. Automation: Create scripts for regular monitoring and alerting
5. Troubleshooting: Understand common issues and their solutions
6. Best Practices: Implement proper monitoring, logging, and error handling
Next Steps
To further enhance your system administration skills:
1. Explore Related Commands: Study `w`, `last`, `users`, and `finger` commands
2. Implement Monitoring: Set up automated user session monitoring
3. Security Integration: Incorporate `who` into your security monitoring toolkit
4. Script Development: Create custom scripts for your specific monitoring needs
5. Log Analysis: Learn to analyze user session patterns and trends
By mastering the `who` command and its various applications, you'll have a powerful tool for maintaining system security, monitoring user activity, and ensuring optimal system performance. Remember to always consider security implications and follow best practices when implementing user monitoring solutions in production environments.