How to show last logins with last
How to Show Last Logins with Last Command
The `last` command is one of the most essential tools for system administrators and security professionals to monitor user activity on Linux and Unix systems. This comprehensive guide will walk you through everything you need to know about using the `last` command to track login history, analyze user behavior, and maintain system security.
Table of Contents
1. [Introduction](#introduction)
2. [Prerequisites](#prerequisites)
3. [Understanding the Last Command](#understanding-the-last-command)
4. [Basic Usage and Syntax](#basic-usage-and-syntax)
5. [Command Options and Parameters](#command-options-and-parameters)
6. [Practical Examples](#practical-examples)
7. [Advanced Use Cases](#advanced-use-cases)
8. [Understanding Output Format](#understanding-output-format)
9. [Related Commands](#related-commands)
10. [Troubleshooting Common Issues](#troubleshooting-common-issues)
11. [Best Practices and Security Tips](#best-practices-and-security-tips)
12. [Conclusion](#conclusion)
Introduction
The `last` command displays a chronological list of user logins and logouts by reading from the system's login records. This powerful utility helps administrators track user activity, investigate security incidents, and monitor system access patterns. Whether you're managing a single server or a complex multi-user environment, understanding how to effectively use the `last` command is crucial for maintaining system security and accountability.
In this comprehensive guide, you'll learn how to use various options and parameters of the `last` command, interpret its output, and apply it in real-world scenarios for system monitoring and security auditing.
Prerequisites
Before diving into the `last` command, ensure you have:
- Access to a Linux or Unix-based system
- Basic familiarity with command-line interface
- Understanding of user accounts and login processes
- Appropriate permissions to read system logs (typically requires root access for full functionality)
- Knowledge of basic terminal navigation
System Requirements
The `last` command is available on most Linux distributions and Unix systems by default. It's part of the `util-linux` package on Linux systems and requires access to the following log files:
- `/var/log/wtmp` - Primary login/logout records
- `/var/log/btmp` - Failed login attempts (for `lastb` command)
- `/var/run/utmp` - Currently logged-in users
Understanding the Last Command
The `last` command reads the `/var/log/wtmp` file, which contains binary records of user logins, logouts, and system reboots. This file is continuously updated by the system whenever users log in or out, making it an invaluable resource for tracking user activity.
Key Features
- Historical Login Data: Shows chronological login/logout history
- User-Specific Filtering: Display activity for specific users
- Terminal Information: Shows which terminal or connection was used
- Duration Tracking: Calculates session duration
- System Events: Records system reboots and shutdowns
- Remote Access Monitoring: Tracks SSH and other remote connections
Basic Usage and Syntax
The basic syntax of the `last` command is straightforward:
```bash
last [options] [username] [tty]
```
Simple Examples
Display the most recent login records:
```bash
last
```
Show login history for a specific user:
```bash
last username
```
Display logins from a specific terminal:
```bash
last tty1
```
Command Options and Parameters
The `last` command offers numerous options to customize output and filter results:
Essential Options
| Option | Description |
|--------|-------------|
| `-n` or `--limit` | Limit number of lines displayed |
| `-f` or `--file` | Specify alternative wtmp file |
| `-t` or `--until` | Display records until specified time |
| `-s` or `--since` | Display records since specified time |
| `-p` or `--present` | Display who was present at specified time |
| `-w` or `--wide` | Display full user and domain names |
| `-i` or `--ip` | Display IP addresses instead of hostnames |
| `-F` or `--fulltimes` | Show full login/logout times |
| `-R` or `--nohostname` | Don't display hostname field |
| `-a` or `--hostlast` | Display hostname in last column |
| `-d` or `--dns` | Translate IP addresses to hostnames |
| `-x` or `--system` | Display system shutdown/runlevel changes |
Time Format Options
When using time-based filtering, you can specify dates and times in various formats:
- `YYYY-MM-DD HH:MM:SS`
- `YYYY-MM-DD HH:MM`
- `YYYY-MM-DD`
- `HH:MM:SS`
- `HH:MM`
Practical Examples
Example 1: Basic Login History
Display the last 10 login records:
```bash
last -n 10
```
Output example:
```
john pts/0 192.168.1.100 Mon Nov 20 14:30 still logged in
mary tty1 Mon Nov 20 13:45 - 14:20 (00:35)
admin pts/1 10.0.0.50 Mon Nov 20 12:15 - 13:30 (01:15)
```
Example 2: User-Specific History
Show all login records for user "john":
```bash
last john
```
Example 3: Time-Based Filtering
Display logins since yesterday:
```bash
last -s yesterday
```
Show logins until a specific date:
```bash
last -t 2023-11-15
```
Display logins within a specific time range:
```bash
last -s "2023-11-01 09:00" -t "2023-11-01 17:00"
```
Example 4: IP Address Display
Show IP addresses instead of hostnames:
```bash
last -i
```
Example 5: Full Time Display
Display complete timestamp information:
```bash
last -F
```
Example 6: System Events
Show system reboots and shutdowns:
```bash
last -x reboot
last -x shutdown
```
Advanced Use Cases
Monitoring Remote Access
Track SSH connections by filtering specific terminals:
```bash
last | grep pts
```
Monitor specific IP ranges:
```bash
last -i | grep "192.168.1"
```
Security Auditing
Identify unusual login patterns:
```bash
Show logins outside business hours
last -s "18:00" -t "08:00"
Monitor weekend activity
last | grep -E "(Sat|Sun)"
```
Failed Login Attempts
Use `lastb` command to view failed login attempts:
```bash
sudo lastb
```
Combining with Other Commands
Create comprehensive reports using pipes:
```bash
Count logins per user
last | awk '{print $1}' | sort | uniq -c | sort -nr
Show unique IP addresses
last -i | awk '{print $3}' | sort | uniq
Generate daily login summary
last -F | grep "$(date '+%a %b %d')"
```
Understanding Output Format
The `last` command output contains several columns of information:
Standard Output Format
```
username tty hostname/IP login_time - logout_time (duration)
```
Column Descriptions
1. Username: The account name that logged in
2. TTY: Terminal or connection type (tty1, pts/0, etc.)
3. Hostname/IP: Source of the connection
4. Login Time: When the session started
5. Logout Time: When the session ended
6. Duration: Total session length
Special Entries
- `reboot`: System restart events
- `shutdown`: System shutdown events
- `wtmp begins`: Start of log file
- `still logged in`: Active sessions
TTY Types
- `tty1-tty6`: Virtual consoles
- `pts/0-pts/n`: Pseudo terminals (SSH, terminal emulators)
- `:0`: Local X11 session
- `console`: System console
Related Commands
lastb Command
View failed login attempts:
```bash
sudo lastb
sudo lastb -n 5 # Last 5 failed attempts
```
who Command
Show currently logged-in users:
```bash
who
who -a # Detailed information
```
w Command
Display current user activity:
```bash
w
w username # Specific user activity
```
users Command
List logged-in usernames:
```bash
users
```
lastlog Command
Show last login for each user:
```bash
lastlog
lastlog -u username # Specific user
```
Troubleshooting Common Issues
Issue 1: Permission Denied
Problem: Cannot access wtmp file
```bash
last: /var/log/wtmp: Permission denied
```
Solution: Run with appropriate privileges
```bash
sudo last
```
Issue 2: Empty or No Output
Problem: No login records displayed
Possible Causes and Solutions:
- Log rotation: Check if wtmp file was rotated
```bash
ls -la /var/log/wtmp*
last -f /var/log/wtmp.1
```
- Corrupted file: Verify file integrity
```bash
file /var/log/wtmp
```
Issue 3: Incorrect Time Display
Problem: Times appear in wrong timezone
Solution: Check system timezone settings
```bash
timedatectl status
sudo timedatectl set-timezone Your/Timezone
```
Issue 4: Missing Remote Hostnames
Problem: IP addresses not resolving to hostnames
Solution: Use DNS resolution option
```bash
last -d
```
Or check DNS configuration:
```bash
cat /etc/resolv.conf
```
Issue 5: Truncated Output
Problem: Long hostnames or usernames are cut off
Solution: Use wide display format
```bash
last -w
```
Best Practices and Security Tips
Regular Monitoring
1. Establish Baselines: Understand normal login patterns
2. Automated Checks: Create scripts for regular monitoring
3. Alert Systems: Set up notifications for unusual activity
Security Monitoring Script
```bash
#!/bin/bash
Monitor for suspicious login activity
Check for logins outside business hours
echo "=== After Hours Logins ==="
last -s "18:00" | head -10
Check for weekend logins
echo "=== Weekend Activity ==="
last | grep -E "(Sat|Sun)" | head -5
Check failed login attempts
echo "=== Recent Failed Logins ==="
sudo lastb -n 10
Check for new IP addresses
echo "=== Unique IPs Today ==="
last -i -s today | awk '{print $3}' | sort | uniq
```
Log Management
1. Regular Backups: Backup wtmp files before rotation
2. Retention Policies: Establish appropriate log retention periods
3. Secure Storage: Protect log files from unauthorized modification
Access Control
1. Limit Access: Restrict who can read login logs
2. Monitor Administrators: Track privileged account usage
3. Regular Audits: Periodically review access patterns
Integration with Security Tools
Combine `last` command output with:
- SIEM Systems: Feed data into security information systems
- Log Analysis Tools: Use with tools like ELK stack
- Monitoring Solutions: Integrate with Nagios, Zabbix, etc.
Performance Considerations
1. Large Files: Use filtering options for large wtmp files
2. Network Lookups: Be cautious with DNS resolution on slow networks
3. Resource Usage: Monitor system resources when processing large logs
Conclusion
The `last` command is an indispensable tool for system administrators and security professionals. Its ability to provide detailed login history makes it essential for monitoring user activity, investigating security incidents, and maintaining system accountability.
Key takeaways from this guide:
- Versatile Filtering: Use various options to filter by user, time, and terminal
- Security Monitoring: Regular monitoring helps identify suspicious activity
- Integration Capabilities: Combine with other tools for comprehensive monitoring
- Troubleshooting Skills: Understanding common issues ensures reliable operation
- Best Practices: Implement proper monitoring and security procedures
By mastering the `last` command and implementing the practices outlined in this guide, you'll be well-equipped to maintain secure and well-monitored systems. Regular use of these techniques will help you quickly identify security issues, track user behavior, and maintain detailed audit trails for compliance and security purposes.
Remember to combine the `last` command with other system monitoring tools and establish regular review procedures to maximize its effectiveness in your security and administration toolkit.