How to see last logins → last, lastlog, faillog
How to See Last Logins: Complete Guide to last, lastlog, and faillog Commands
Table of Contents
1. [Introduction](#introduction)
2. [Prerequisites](#prerequisites)
3. [Understanding Login Tracking](#understanding-login-tracking)
4. [The last Command](#the-last-command)
5. [The lastlog Command](#the-lastlog-command)
6. [The faillog Command](#the-faillog-command)
7. [Practical Examples and Use Cases](#practical-examples-and-use-cases)
8. [Advanced Usage and Options](#advanced-usage-and-options)
9. [Log File Locations and Management](#log-file-locations-and-management)
10. [Security Considerations](#security-considerations)
11. [Troubleshooting Common Issues](#troubleshooting-common-issues)
12. [Best Practices](#best-practices)
13. [Conclusion](#conclusion)
Introduction
Monitoring user login activity is a critical aspect of system administration and security management on Linux systems. Whether you're investigating security incidents, auditing user access, or simply maintaining awareness of system usage, understanding how to track login information is essential for any system administrator.
This comprehensive guide will teach you how to effectively use three powerful Linux commands: `last`, `lastlog`, and `faillog`. These tools provide different perspectives on user login activity, from successful logins and session information to failed authentication attempts. By mastering these commands, you'll gain valuable insights into your system's access patterns and potential security threats.
Throughout this article, you'll learn not only the basic syntax and usage of these commands but also advanced techniques, practical applications, and best practices for login monitoring. We'll cover real-world scenarios, troubleshooting common issues, and security considerations that every administrator should know.
Prerequisites
Before diving into the login monitoring commands, ensure you have the following:
System Requirements
- A Linux-based operating system (Ubuntu, CentOS, RHEL, Debian, etc.)
- Terminal or SSH access to the system
- Basic familiarity with Linux command-line interface
User Permissions
- Standard user privileges for basic login information viewing
- Root or sudo privileges for comprehensive system-wide login monitoring
- Administrative access for modifying log retention policies
Essential Knowledge
- Basic understanding of Linux file system structure
- Familiarity with log files and their locations
- Understanding of user accounts and authentication processes
Understanding Login Tracking
Linux systems maintain detailed records of user login activities through various log files and databases. These records serve multiple purposes:
Types of Login Information
- Successful logins: When users successfully authenticate and access the system
- Failed login attempts: Authentication failures that may indicate security threats
- Session duration: How long users remain logged into the system
- Login sources: Where login attempts originate (local, SSH, etc.)
- User activity patterns: Frequency and timing of user access
Log Storage Mechanisms
Linux systems use several mechanisms to store login information:
- wtmp database: Binary file containing login/logout records
- lastlog database: Binary file tracking last login information per user
- faillog database: Binary file recording failed login attempts
- Text-based logs: Human-readable log files in `/var/log/`
The last Command
The `last` command is one of the most frequently used tools for viewing login history. It reads from the wtmp file to display information about user logins, logouts, and system reboots.
Basic Syntax
```bash
last [options] [username] [tty]
```
Fundamental Usage
To view the most recent login records:
```bash
last
```
This command displays output similar to:
```
john pts/0 192.168.1.100 Tue Dec 12 14:30 still logged in
mary tty1 Tue Dec 12 09:15 - 17:45 (08:30)
root pts/1 10.0.0.50 Mon Dec 11 22:10 - 23:45 (01:35)
reboot system boot 5.4.0-74-generic Mon Dec 11 08:00 still running
```
Understanding last Command Output
Each line in the output contains:
- Username: The user who logged in
- Terminal: The terminal or connection type (pts/0, tty1, etc.)
- Source: IP address or hostname of login origin
- Login time: When the session started
- Logout time: When the session ended (or current status)
- Duration: Total session length
Common last Command Options
Limiting Output Lines
```bash
Show only the last 10 login records
last -n 10
Alternative syntax
last -10
```
Viewing Specific User Activity
```bash
Show login history for specific user
last john
Show login history for multiple users
last john mary root
```
Filtering by Terminal
```bash
Show logins from specific terminal
last pts/0
Show console logins only
last tty1
```
Time-Based Filtering
```bash
Show logins since specific date
last -s 2023-12-01
Show logins until specific date
last -t 2023-12-31
Show logins within date range
last -s 2023-12-01 -t 2023-12-31
```
Displaying Full Hostnames
```bash
Show complete hostnames instead of IP addresses
last -a
Show IP addresses in numeric format
last -i
```
The lastlog Command
The `lastlog` command provides information about the last login time for all users on the system, reading from the lastlog database file.
Basic Syntax
```bash
lastlog [options]
```
Fundamental Usage
To view last login information for all users:
```bash
lastlog
```
Sample output:
```
Username Port From Latest
root pts/0 192.168.1.100 Tue Dec 12 14:30:25 +0000 2023
daemon Never logged in
bin Never logged in
john pts/1 10.0.0.25 Mon Dec 11 16:45:12 +0000 2023
mary tty1 Sun Dec 10 09:20:33 +0000 2023
```
lastlog Command Options
Viewing Specific Users
```bash
Show last login for specific user
lastlog -u john
Show last login for user by UID
lastlog -u 1001
```
Time-Based Filtering
```bash
Show users who logged in within last 7 days
lastlog -t 7
Show users who haven't logged in for 30 days
lastlog -b 30
```
Formatting Options
```bash
Display times in specified format
lastlog -t 30 -u john
Show users within UID range
lastlog -u 1000-2000
```
The faillog Command
The `faillog` command displays and manages failed login attempt records, which is crucial for security monitoring.
Basic Syntax
```bash
faillog [options]
```
Fundamental Usage
To view failed login attempts for all users:
```bash
faillog
```
Sample output:
```
Login Failures Maximum Latest On
root 3 0 12/12/23 14:25:33 pts/0
john 0 0
mary 1 0 12/11/23 16:30:15 ssh:notty
```
Understanding faillog Output
- Login: Username with failed attempts
- Failures: Number of consecutive failed attempts
- Maximum: Maximum allowed failures before lockout (0 = unlimited)
- Latest: Time of most recent failed attempt
- On: Terminal or connection type where failure occurred
faillog Command Options
Viewing Specific Users
```bash
Show failed logins for specific user
faillog -u john
Show failed logins for UID range
faillog -u 1000-2000
```
Managing Failure Limits
```bash
Set maximum failures before lockout (requires root)
sudo faillog -u john -M 5
Remove failure limit (unlimited attempts)
sudo faillog -u john -M 0
```
Resetting Failure Counts
```bash
Reset failure count for specific user
sudo faillog -u john -r
Reset failure counts for all users
sudo faillog -a -r
```
Practical Examples and Use Cases
Security Incident Investigation
When investigating potential security breaches, combine all three commands for comprehensive analysis:
```bash
Check recent login activity
last -n 50 | grep -E "(192\.168\.1\.|10\.0\.0\.)"
Identify users with recent failed attempts
faillog | grep -v "0$" | grep -v "root"
Check when specific suspicious user last logged in
lastlog -u suspicious_user
```
Regular Security Auditing
Create a security audit script:
```bash
#!/bin/bash
echo "=== Security Audit Report ==="
echo "Generated on: $(date)"
echo
echo "=== Recent Failed Login Attempts ==="
faillog | awk '$2 > 0 {print}'
echo
echo "=== Recent Successful Logins ==="
last -n 20
echo
echo "=== Users Who Haven't Logged In Recently ==="
lastlog -t 30 | grep -v "Never logged in"
```
Monitoring Remote Access
Track SSH and remote login patterns:
```bash
Show only SSH logins
last | grep pts
Show logins from external IP addresses
last -i | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}"
Monitor specific IP range
last | grep "192.168.1."
```
User Activity Analysis
Analyze user behavior patterns:
```bash
Show login frequency for specific user
last john | head -20
Check weekend login activity
last -s $(date -d "last saturday" +%Y-%m-%d)
Identify unusual login times
last | grep -E "(0[0-6]:|2[2-3]:)"
```
Advanced Usage and Options
Combining Commands with Pipes and Filters
Advanced Filtering Techniques
```bash
Show only root logins from external sources
last root | grep -v "console\|tty"
Count login attempts per user
last | awk '{print $1}' | sort | uniq -c | sort -nr
Find concurrent login sessions
last | grep "still logged in"
```
Time-Based Analysis
```bash
Show login activity for specific month
last -s 2023-12-01 -t 2023-12-31 | grep -v "wtmp begins"
Analyze login patterns by hour
last | awk '{print $4}' | cut -d: -f1 | sort | uniq -c
Find weekend logins
last | grep -E "(Sat|Sun)"
```
Creating Custom Reports
Daily Login Summary Script
```bash
#!/bin/bash
DATE=$(date +%Y-%m-%d)
LOGFILE="/var/log/login-report-$DATE.log"
{
echo "Daily Login Report for $DATE"
echo "================================"
echo
echo "Unique Users Logged In Today:"
last -s $DATE | awk '{print $1}' | sort | uniq | grep -v "^$"
echo
echo "Failed Login Attempts:"
faillog | awk '$2 > 0 {print $1, $2, $4, $5}'
echo
echo "Active Sessions:"
last | grep "still logged in"
} > $LOGFILE
echo "Report saved to $LOGFILE"
```
Weekly Security Review
```bash
#!/bin/bash
WEEK_AGO=$(date -d "7 days ago" +%Y-%m-%d)
echo "=== Weekly Security Review ==="
echo "Period: $WEEK_AGO to $(date +%Y-%m-%d)"
echo
echo "Top 10 Most Active Users:"
last -s $WEEK_AGO | awk '{print $1}' | sort | uniq -c | sort -nr | head -10
echo
echo "External Login Sources:"
last -s $WEEK_AGO -i | grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" | awk '{print $3}' | sort | uniq -c | sort -nr
echo
echo "Failed Login Summary:"
faillog | awk '$2 > 0 {total += $2; users++} END {print "Total failures:", total, "Affected users:", users}'
```
Log File Locations and Management
Understanding Log File Structure
wtmp File Location and Management
```bash
Default location
ls -la /var/log/wtmp
Check wtmp file size
du -h /var/log/wtmp
Rotate wtmp manually (requires root)
sudo logrotate /etc/logrotate.conf
```
lastlog File Management
```bash
Check lastlog file
ls -la /var/log/lastlog
View lastlog file size
du -h /var/log/lastlog
Note: lastlog is sparse file, actual disk usage may be less
du -h --apparent-size /var/log/lastlog
```
faillog File Administration
```bash
Examine faillog file
ls -la /var/log/faillog
Check faillog configuration
cat /etc/login.defs | grep -i fail
```
Log Rotation and Archival
Configuring Log Rotation
Create or modify `/etc/logrotate.d/wtmp`:
```bash
/var/log/wtmp {
monthly
create 0664 root utmp
minsize 1M
rotate 12
compress
delaycompress
}
```
Manual Log Management
```bash
Archive current wtmp
sudo cp /var/log/wtmp /var/log/wtmp.$(date +%Y%m%d)
Clear wtmp (use with caution)
sudo truncate -s 0 /var/log/wtmp
Backup important logs
sudo tar -czf login-logs-backup-$(date +%Y%m%d).tar.gz /var/log/{wtmp,lastlog,faillog}
```
Security Considerations
Protecting Log Files
File Permissions and Ownership
```bash
Check current permissions
ls -la /var/log/{wtmp,lastlog,faillog}
Set appropriate permissions (if needed)
sudo chmod 644 /var/log/wtmp
sudo chmod 644 /var/log/lastlog
sudo chmod 600 /var/log/faillog
sudo chown root:utmp /var/log/wtmp
sudo chown root:root /var/log/{lastlog,faillog}
```
Preventing Log Tampering
```bash
Set immutable attribute (use carefully)
sudo chattr +a /var/log/wtmp
Remove immutable attribute
sudo chattr -a /var/log/wtmp
Check file attributes
lsattr /var/log/wtmp
```
Monitoring and Alerting
Automated Monitoring Script
```bash
#!/bin/bash
Monitor for suspicious login activity
THRESHOLD=5
RECENT_FAILURES=$(faillog | awk '$2 > 0 {count++} END {print count+0}')
if [ "$RECENT_FAILURES" -gt "$THRESHOLD" ]; then
echo "ALERT: $RECENT_FAILURES users with failed login attempts"
faillog | awk '$2 > 0 {print $1, $2, "failures"}'
# Send notification (customize as needed)
# mail -s "Login Alert" admin@company.com < /tmp/alert.txt
fi
Check for unusual login times
NIGHT_LOGINS=$(last -n 100 | grep -E "(0[0-5]:|2[3-4]:)" | wc -l)
if [ "$NIGHT_LOGINS" -gt 0 ]; then
echo "WARNING: $NIGHT_LOGINS night-time logins detected"
fi
```
Compliance and Auditing
Meeting Compliance Requirements
```bash
Generate compliance report
#!/bin/bash
REPORT_DATE=$(date +%Y-%m-%d)
REPORT_FILE="compliance-report-$REPORT_DATE.txt"
{
echo "Login Activity Compliance Report"
echo "Generated: $(date)"
echo "System: $(hostname)"
echo "================================"
echo
echo "1. User Account Activity (Last 30 days):"
lastlog -t 30
echo
echo "2. Failed Authentication Attempts:"
faillog | awk '$2 > 0'
echo
echo "3. Administrative Access Log:"
last root | head -20
echo
echo "4. Remote Access Summary:"
last | grep pts | head -20
} > "$REPORT_FILE"
echo "Compliance report saved to $REPORT_FILE"
```
Troubleshooting Common Issues
Command Not Found Errors
Installing Missing Packages
```bash
On Ubuntu/Debian
sudo apt-get update
sudo apt-get install util-linux
On CentOS/RHEL
sudo yum install util-linux
or for newer versions
sudo dnf install util-linux
```
Missing or Corrupted Log Files
Diagnosing Log File Issues
```bash
Check if log files exist
ls -la /var/log/{wtmp,lastlog,faillog}
Verify file integrity
file /var/log/wtmp
file /var/log/lastlog
file /var/log/faillog
Check file system errors
sudo fsck /var/log
```
Recreating Missing Log Files
```bash
Recreate wtmp file
sudo touch /var/log/wtmp
sudo chown root:utmp /var/log/wtmp
sudo chmod 664 /var/log/wtmp
Recreate lastlog file
sudo touch /var/log/lastlog
sudo chown root:root /var/log/lastlog
sudo chmod 644 /var/log/lastlog
Recreate faillog file
sudo touch /var/log/faillog
sudo chown root:root /var/log/faillog
sudo chmod 600 /var/log/faillog
```
Permission Denied Errors
Resolving Access Issues
```bash
Check current user permissions
id
groups
Add user to appropriate groups
sudo usermod -a -G adm,systemd-journal username
Use sudo for administrative commands
sudo last
sudo lastlog
sudo faillog
```
Empty or Incomplete Output
Troubleshooting Data Issues
```bash
Check log file sizes
ls -lh /var/log/{wtmp,lastlog,faillog}
Verify logging is enabled
grep -i log /etc/rsyslog.conf
systemctl status rsyslog
Check system time and timezone
timedatectl status
date
```
Performance Issues with Large Log Files
Optimizing Large Log Queries
```bash
Use head/tail for large files
last | head -100
last | tail -100
Limit output with -n option
last -n 50
Use specific time ranges
last -s $(date -d "1 week ago" +%Y-%m-%d)
Filter before processing
last | grep "$(date +%b\ %d)"
```
Best Practices
Regular Monitoring Procedures
Establishing Monitoring Routines
1. Daily Checks: Review failed login attempts and unusual activity
2. Weekly Reviews: Analyze login patterns and user behavior
3. Monthly Audits: Comprehensive security assessment and compliance review
4. Quarterly Reports: Long-term trend analysis and policy updates
Automated Monitoring Implementation
```bash
Add to crontab for daily monitoring
0 8 * /usr/local/bin/daily-login-check.sh
Weekly security review
0 9 1 /usr/local/bin/weekly-security-review.sh
Monthly compliance report
0 10 1 /usr/local/bin/monthly-compliance-report.sh
```
Log Management Best Practices
Retention Policies
- Short-term logs: Keep detailed logs for 30-90 days
- Long-term archives: Compress and store summaries for 1-7 years
- Critical events: Permanent retention for security incidents
Storage Considerations
```bash
Monitor log disk usage
df -h /var/log
du -sh /var/log/*
Implement log rotation
sudo logrotate -f /etc/logrotate.conf
Archive old logs
find /var/log -name ".log." -mtime +30 -exec gzip {} \;
```
Security Hardening
Access Control
- Limit access to log files using appropriate permissions
- Use sudo for administrative log access
- Implement log forwarding to secure central servers
- Enable file integrity monitoring for critical logs
Alerting and Response
```bash
Example alert script
#!/bin/bash
Place in /usr/local/bin/login-alert.sh
FAILED_THRESHOLD=10
RECENT_FAILURES=$(faillog | awk '$2 > '$FAILED_THRESHOLD' {count++} END {print count+0}')
if [ "$RECENT_FAILURES" -gt 0 ]; then
logger -p auth.warning "High number of failed login attempts detected"
# Add notification mechanism here
fi
```
Documentation and Reporting
Maintaining Documentation
1. Log Analysis Procedures: Document standard operating procedures
2. Incident Response: Create templates for security incident investigation
3. Compliance Mapping: Map log data to regulatory requirements
4. Training Materials: Develop team training on login monitoring
Report Templates
Create standardized reports for different audiences:
- Technical Reports: Detailed analysis for system administrators
- Management Summaries: High-level security posture for executives
- Compliance Reports: Formatted for regulatory requirements
- Incident Reports: Structured investigation documentation
Conclusion
Mastering the `last`, `lastlog`, and `faillog` commands is essential for effective Linux system administration and security management. These powerful tools provide comprehensive insights into user login activity, enabling administrators to monitor system access, investigate security incidents, and maintain compliance with organizational policies.
Throughout this guide, we've explored the fundamental usage of each command, advanced techniques for data analysis, and practical applications for real-world scenarios. The key takeaways include:
Essential Skills Developed
- Comprehensive Login Monitoring: Using all three commands together for complete visibility
- Security Investigation: Techniques for analyzing suspicious activity and security incidents
- Automated Reporting: Creating scripts and procedures for regular monitoring
- Log Management: Understanding log file locations, rotation, and archival strategies
Security Benefits Achieved
- Proactive Threat Detection: Identifying potential security issues before they escalate
- Compliance Support: Meeting regulatory requirements for access monitoring
- Incident Response: Rapid investigation capabilities for security events
- User Behavior Analysis: Understanding normal patterns to identify anomalies
Next Steps for Implementation
1. Establish Monitoring Procedures: Implement regular checks using the techniques covered
2. Create Automated Scripts: Develop custom monitoring and reporting tools
3. Configure Alerting: Set up notifications for suspicious activities
4. Document Processes: Create standard operating procedures for your environment
5. Train Team Members: Ensure all administrators understand these monitoring capabilities
Remember that effective login monitoring is an ongoing process that requires regular attention and continuous improvement. The commands and techniques presented in this guide provide a solid foundation, but they should be adapted to your specific environment, security requirements, and compliance needs.
By implementing these practices and maintaining vigilant monitoring of login activities, you'll significantly enhance your system's security posture and be well-prepared to detect, investigate, and respond to potential security threats. The investment in mastering these tools will pay dividends in improved security awareness and incident response capabilities.
Continue to explore advanced logging solutions, consider implementing centralized log management systems, and stay updated with the latest security monitoring best practices to maintain an effective security monitoring program.