Overview
last searches back through the /var/log/wtmp file (or specified file) and displays a list of all users logged in (and out) since that file was created. It shows user login sessions, system boots, and shutdowns with timestamps, terminal information, and duration of sessions. This command is essential for security auditing, user activity monitoring, and investigating unauthorized access.
Understanding wtmp
The wtmp file is a binary log maintained by the login system that records all logins, logouts, system boots, and shutdowns. It rotates when it gets too large (becoming wtmp.1, wtmp.2.gz, etc.). The lastb command reads from btmp (bad login attempts), while last reads wtmp (successful logins).
Example 1: Show Recent Login History
$ last$ last | head -20 # Show first 20 entries
Displays a listing of all users who have logged in and out, showing most recent activity first. Output includes username, terminal, source IP/hostname, login time, logout time, and session duration.
Field descriptions:
- Column 1: Username or "reboot" for system boots
- Column 2: Terminal (tty, pts) or "system boot"
- Column 3: Source hostname or IP address
- Column 4-5: Login date and time
- Column 6-7: Logout time or "still logged in"
- Column 8: Duration in (HH:MM) format
Example 2: Show Specific User's Login History
$ last craig$ last root$ last www-data # Service account logins
Filters output to show only login sessions for the specified username. Essential for tracking individual user activity and investigating potential security issues.
Security investigation uses:
- Track when a specific user accessed the system
- Identify unusual login times or locations
- Verify user claims about system access
- Monitor privileged account usage (root, admin users)
- Audit service account activity
Example 3: Limit Number of Lines Displayed
$ last -n 10$ last -10 # Short form$ last craig -5 # Last 5 logins for craig$ last --limit 20 # Long form
The -n option limits output to the specified number of lines. Without this, last can display hundreds or thousands of entries depending on wtmp file size.
Performance consideration: On systems with large wtmp files, using -n significantly improves response time by limiting the amount of data processed and displayed.
Example 4: Show Login History for Specific Terminal
$ last pts/0$ last tty1 # Physical console$ last pts/2 # Specific pseudo-terminal
Filters output to show only sessions on a specific terminal device. Useful for tracking activity on particular connection points.
Terminal types:
- tty1-tty6: Physical console terminals (Ctrl+Alt+F1 through F6)
- pts/N: Pseudo-terminals (SSH sessions, terminal emulators)
- :0: X Window System display (graphical login)
Example 5: Show Only System Reboots
$ last reboot$ last reboot -10 # Last 10 reboots$ last shutdown # System shutdown events
Displays system boot history with kernel version and uptime information. Critical for understanding system stability and tracking unexpected reboots.
Analysis insights:
- Frequent reboots may indicate hardware issues, kernel panics, or maintenance windows
- Kernel version changes show when system updates occurred
- "still running" indicates current boot session
- Short uptimes may suggest stability problems
- Compare with expected maintenance schedules
Example 6: Display Full Login/Logout Times
$ last -F$ last --fulltime craig
The -F option displays full date and time information instead of abbreviated format. Shows complete timestamps with seconds precision.
When to use full timestamps:
- Security forensics requiring precise timing
- Correlating events across multiple systems
- Generating detailed audit reports
- Compliance requirements for complete logs
- Investigating incidents down to the second
Example 7: Display Hostname in IP Address Format
$ last -i$ last -i craig # IP addresses for specific user
The -i option displays source addresses as IP addresses instead of attempting hostname resolution. Useful when DNS is unavailable or slow, or when you need raw IP information.
Security analysis benefits:
- Identify geographic location of login sources
- Detect logins from unexpected IP ranges
- Correlate with firewall logs using IP addresses
- Spot suspicious patterns (multiple IPs for one user)
- Works even when DNS resolution fails
Example 8: Show Logins Since Specific Date/Time
$ last -s "2025-11-01"$ last --since "2025-11-01 10:00:00"$ last -s yesterday craig$ last -s "3 days ago"
The -s (--since) option filters entries to show only logins occurring after the specified date/time. Accepts various date formats.
Supported formats:
- YYYY-MM-DD: ISO date format
- YYYY-MM-DD HH:MM:SS: Full timestamp
- yesterday, today, tomorrow: Relative dates
- "N days ago", "N hours ago": Relative time
Example 9: Show Logins Until Specific Date/Time
$ last -t "2025-11-07"$ last --until "2025-11-07 18:00:00"$ last -s "2025-11-01" -t "2025-11-07" # Date range$ last craig -s yesterday -t today
The -t (--until) option filters entries to show only logins before the specified date/time. Combine with -s to create precise date ranges for analysis.
Date range analysis: Examining specific time windows is crucial for:
- Generating periodic access reports (weekly, monthly)
- Investigating specific incident timeframes
- Compliance audits requiring historical data
- Performance analysis during known issues
- Correlating user activity with system events
Example 10: Read from Alternative wtmp Files
$ last -f /var/log/wtmp.1$ last -f /var/log/wtmp.1 craig$ last --file /backup/wtmp-2025-10$ zcat /var/log/wtmp.2.gz | last -f - # Read from pipe (some versions)
The -f (--file) option allows reading from alternative wtmp files instead of the default /var/log/wtmp. Essential for examining historical login data from rotated log files.
Log rotation understanding:
- /var/log/wtmp: Current active log file
- /var/log/wtmp.1: Previous rotation (most recent archived)
- /var/log/wtmp.2.gz: Older rotation (compressed)
- Rotation typically occurs monthly or when file size limit reached
Related Commands and Files
lastb - Failed Login Attempts
$ sudo lastb # Show failed login attempts$ sudo lastb -n 20 # Last 20 failed attempts$ sudo lastb root # Failed root logins
The lastb command reads from /var/log/btmp (bad logins) and shows failed login attempts. Critical for detecting brute-force attacks and unauthorized access attempts. Requires root privileges to read btmp file.
Indicators of attacks:
- Multiple failed attempts from same IP
- Failed attempts to common usernames (admin, root, test)
- Rapid succession of failed logins
- Failed attempts from unexpected geographic locations
who and w Commands
$ who # Currently logged-in users$ w # More detailed current user info$ users # Simple list of logged-in users
who: Shows currently logged-in users with login time and terminal
w: Shows current users plus what they're doing, load averages, and idle time
users: Space-separated list of usernames currently logged in
Important Files
- /var/log/wtmp: Binary log of successful logins/logouts (read by last)
- /var/log/btmp: Binary log of failed login attempts (read by lastb)
- /var/log/auth.log (Debian/Ubuntu): Text authentication logs
- /var/log/secure (RHEL/CentOS): Text security and authentication logs
- /var/run/utmp: Current login information (read by who, w)
Security and Privacy Considerations
- Log integrity: wtmp/btmp files can be modified by attackers. Cross-reference with other logs (syslog, journal) and consider centralized logging.
- Privacy concerns: These logs contain sensitive user activity information. Protect access with appropriate permissions and consider retention policies.
- Regular monitoring: Automated monitoring of login patterns can detect compromises early. Set up alerts for unusual activity.
- Log rotation: Configure appropriate retention periods balancing security needs with storage and privacy concerns.
- Forensic value: During incidents, preserve wtmp/btmp files before they rotate. Copy to secure storage for investigation.
Practical Security Monitoring Scripts
#!/bin/bash
# Monitor for root logins from unexpected locations
last -i root | grep -v "192.168.1" | grep -v "10.0.0" | mail -s "Alert: Root login from external IP" admin@example.com
# Count failed login attempts in last hour
sudo lastb -s "1 hour ago" | wc -l
# Show all unique IPs that failed login attempts
sudo lastb -i | awk '{print $3}' | sort -u
# Generate daily access report
last -s yesterday -t today -F > /var/log/reports/access-$(date +%Y%m%d).txt
Pro Tips for Using last
- Combine with grep: "last | grep 'Nov 7'" to filter by specific dates
- Use with awk: Extract specific fields for custom reports
- Time zone awareness: last displays times in system local timezone
- Multiple filters: "last craig pts/0 -10" combines user and terminal filters
- Session duration analysis: Look for unusually long or short sessions
- Automated auditing: Schedule regular last reports via cron
- Correlation: Cross-reference with journalctl and auth.log for complete picture
- Baseline establishment: Regular monitoring helps identify anomalies
- Geographic checking: Use IP addresses with geo-location tools
- Compliance: Many regulations require login tracking - last provides this
Common Output Indicators
- "still logged in": User currently logged in
- "crash": System crashed without clean shutdown
- "down": System shutdown occurred
- "gone - no logout": Session terminated abnormally
- "system boot": System reboot record
- Empty source field: Local login (console)
- :0: X Window graphical session