The `last` Command: Complete Guide to Linux Login History

Master the `last` command for Linux system administration. Learn to track user logins, monitor security, and audit system access with practical examples.

The last Command: Comprehensive Guide to Login History

The last command is a fundamental system administration utility in Unix and Linux systems that provides detailed information about user login sessions, system reboots, and shutdown events. This command reads from system log files to display a chronological history of user activities, making it an essential tool for security auditing, system monitoring, and troubleshooting.

Overview and Purpose

The last command serves multiple critical functions in system administration:

- Security Auditing: Track unauthorized access attempts and monitor user behavior - System Monitoring: Observe login patterns and system usage statistics - Troubleshooting: Identify connection issues and system problems - Compliance: Maintain records for regulatory requirements - Performance Analysis: Understand system usage patterns

How last Works

The last command operates by reading binary log files that contain login records. These files are typically located in /var/log/ directory and include:

- /var/log/wtmp: Primary log file for login records - /var/log/btmp: Failed login attempts (used by lastb) - /var/log/utmp: Currently logged-in users

The command processes these binary files and presents the information in a human-readable format, showing login sessions in reverse chronological order (most recent first).

Basic Syntax and Usage

Standard Syntax

`bash last [options] [username] [tty] `

Basic Examples

`bash

Display all recent login records

last

Show last logins for specific user

last username

Show last logins on specific terminal

last tty1

Display last 10 login records

last -n 10 `

Command Options and Parameters

Core Options

| Option | Long Form | Description | |--------|-----------|-------------| | -n | --limit | Specify number of lines to display | | -f | --file | Read from alternative log file | | -t | --until | Display records until specified time | | -p | --present | Display records at specified time | | -w | --fullnames | Display full user and domain names | | -a | --hostlast | Display hostname in last column | | -d | --dns | Translate IP addresses to hostnames | | -i | --ip | Display IP addresses instead of hostnames | | -o | --nohostname | Don't display hostname field | | -R | --nohostname | Don't display hostname field | | -x | --system | Display system shutdown/runlevel entries |

Time Format Options

| Option | Description | Example | |--------|-------------|---------| | -t YYYYMMDDHHMMSS | Until specific date/time | -t 20231201120000 | | -s YYYYMMDDHHMMSS | Since specific date/time | -s 20231201000000 | | -p YYYYMMDDHHMMSS | At specific date/time | -p 20231201120000 |

Detailed Command Examples

Basic Usage Examples

`bash

Show all login records

last

Show last 5 login records

last -5

Show last 20 login records

last -n 20 `

User-Specific Queries

`bash

Show login history for user 'john'

last john

Show login history for multiple users

last john mary admin

Show login history for root user

last root `

Terminal-Specific Queries

`bash

Show logins on console

last console

Show logins on specific TTY

last tty1

Show SSH logins

last | grep pts `

Time-Based Filtering

`bash

Show logins until December 1, 2023 at noon

last -t 20231201120000

Show logins since December 1, 2023

last -s 20231201000000

Show logins for specific day

last -s 20231201000000 -t 20231201235959 `

Advanced Filtering Examples

`bash

Show only system events (reboots, shutdowns)

last -x

Show full hostnames and usernames

last -w

Display IP addresses instead of hostnames

last -i

Show logins with DNS resolution

last -d

Read from alternative log file

last -f /var/log/wtmp.1 `

Understanding Output Format

Standard Output Columns

| Column | Description | Example | |--------|-------------|---------| | Username | Login account name | john, root, admin | | Terminal | Connection type/terminal | pts/0, tty1, console | | Hostname/IP | Source of connection | 192.168.1.100, workstation.local | | Login Time | Session start time | Mon Dec 4 09:15 | | Logout Time | Session end time | 10:30 (01:15) | | Duration | Session length | (01:15) |

Sample Output Analysis

` john pts/0 192.168.1.100 Mon Dec 4 09:15 - 10:30 (01:15) mary pts/1 workstation Mon Dec 4 08:45 still logged in root console - Sun Dec 3 23:00 - 07:30 (08:30) reboot system boot 4.15.0-generic Sun Dec 3 22:58 - 10:35 (11:37) `

Special Entries

| Entry Type | Description | Example | |------------|-------------|---------| | reboot | System restart | reboot system boot | | shutdown | System shutdown | shutdown system down | | still logged in | Active session | Current user session | | gone - no logout | Abnormal termination | Crashed or forced logout | | crash | System crash | Unexpected shutdown |

Practical Use Cases

Security Monitoring

`bash

Monitor root login attempts

last root

Check for unusual login times

last | grep "Sat\|Sun"

Identify failed login patterns

lastb | head -20

Monitor specific IP address

last | grep "192.168.1.50" `

System Administration

`bash

Check system uptime patterns

last -x | grep reboot

Monitor user activity levels

last | awk '{print $1}' | sort | uniq -c | sort -nr

Check for concurrent logins

last | grep "still logged in"

Audit login sources

last | awk '{print $3}' | sort | uniq -c | sort -nr `

Troubleshooting Scenarios

`bash

Investigate connection issues

last username | head -10

Check system stability

last -x | grep -E "(reboot|shutdown)"

Analyze login frequency

last -n 100 | grep username

Check for session anomalies

last | grep "gone - no logout" `

Advanced Techniques and Tips

Combining with Other Commands

`bash

Count logins per user

last | awk '{print $1}' | sort | uniq -c | sort -nr

Find most active login hours

last | awk '{print $4}' | cut -d: -f1 | sort | uniq -c

Extract unique IP addresses

last | awk '{print $3}' | grep -E '^[0-9]' | sort -u

Monitor login duration patterns

last | grep -v "still logged in" | awk '{print $10}' | grep -E '^\([0-9]' `

Creating Custom Reports

`bash

Daily login summary

last -s $(date +%Y%m%d000000) | grep -v "wtmp begins"

Weekly activity report

last -s $(date -d "7 days ago" +%Y%m%d000000)

Generate CSV format output

last -n 50 | awk '{print $1","$2","$3","$4" "$5" "$6","$7","$8","$9}' `

Automation Scripts

`bash #!/bin/bash

Monitor suspicious login activity

Check for logins outside business hours

echo "After-hours logins:" last | awk '$4 ~ /^(1[89]|2[0-3]|0[0-7]):/ {print}'

Check for weekend logins

echo "Weekend logins:" last | grep -E "(Sat|Sun)"

Check for multiple concurrent sessions

echo "Users with multiple sessions:" last | grep "still logged in" | awk '{print $1}' | sort | uniq -c | awk '$1>1' `

Log File Management

Understanding Log Rotation

Most systems implement log rotation to manage disk space:

`bash

Check log file sizes

ls -lh /var/log/wtmp*

View rotated logs

last -f /var/log/wtmp.1

Combine multiple log files

last -f /var/log/wtmp && last -f /var/log/wtmp.1 `

Log File Locations by System

| System Type | Primary Log Location | Alternative Locations | |-------------|---------------------|---------------------| | Ubuntu/Debian | /var/log/wtmp | /var/log/wtmp.1 | | CentOS/RHEL | /var/log/wtmp | /var/log/wtmp-* | | FreeBSD | /var/log/wtmp | /var/log/wtmp.0.bz2 | | macOS | /var/log/wtmp | System-specific locations |

Security Considerations

Protecting Log Files

`bash

Check log file permissions

ls -l /var/log/wtmp

Secure log file access

sudo chmod 644 /var/log/wtmp sudo chown root:utmp /var/log/wtmp `

Detecting Tampering

`bash

Monitor log file integrity

sudo find /var/log -name "wtmp*" -exec ls -l {} \;

Check for unusual gaps in logs

last | grep "wtmp begins"

Verify log continuity

last -x | grep reboot `

Privacy and Compliance

Organizations must consider privacy implications:

- Data Retention: Establish clear policies for log retention periods - Access Control: Limit access to authorized personnel only - Audit Trails: Maintain records of who accesses login logs - Anonymization: Consider anonymizing logs for analysis purposes

Troubleshooting Common Issues

Empty or Missing Output

`bash

Check if wtmp file exists

ls -l /var/log/wtmp

Verify file permissions

stat /var/log/wtmp

Check if logging is enabled

grep -i log /etc/rsyslog.conf `

Corrupted Log Files

`bash

Test log file integrity

last -f /var/log/wtmp | head -1

Use alternative log files

last -f /var/log/wtmp.1

Rebuild logs if necessary (system-dependent)

sudo service rsyslog restart `

Performance Issues

`bash

Limit output for large logs

last -n 100

Use specific user filters

last username

Process logs in chunks

last -s 20231201000000 -t 20231201235959 `

Related Commands and Tools

Complementary Commands

| Command | Purpose | Example Usage | |---------|---------|---------------| | lastb | Show failed login attempts | lastb -n 10 | | who | Show currently logged users | who -a | | w | Show logged users and activity | w | | users | List logged-in users | users | | finger | User information lookup | finger username | | id | User and group information | id username |

Advanced Analysis Tools

`bash

Using lastb for failed attempts

sudo lastb | head -20

Combining with who for current state

who && echo "---" && last -5

Using journalctl for systemd systems

journalctl -u ssh | grep "Accepted\|Failed" `

Best Practices and Recommendations

Regular Monitoring Practices

1. Daily Reviews: Check recent login activity daily 2. Automated Alerts: Set up alerts for unusual patterns 3. Regular Audits: Perform comprehensive reviews weekly 4. Documentation: Maintain records of significant events

Security Monitoring Checklist

- [ ] Monitor root account logins - [ ] Check for after-hours access - [ ] Verify login sources and locations - [ ] Investigate failed login attempts - [ ] Review system reboot patterns - [ ] Check for concurrent sessions - [ ] Audit privileged account usage - [ ] Monitor service account activity

Performance Optimization

`bash

Use time ranges for large datasets

last -s $(date -d "1 week ago" +%Y%m%d000000)

Limit output size

last -n 50

Process specific users only

last username1 username2

Use grep for pattern matching

last | grep "Dec 4" `

Conclusion

The last command is an indispensable tool for system administrators, security professionals, and anyone responsible for maintaining Unix or Linux systems. Its ability to provide detailed login history, track system events, and support various filtering options makes it essential for security auditing, troubleshooting, and compliance requirements.

Understanding the various options, output formats, and advanced techniques enables effective system monitoring and security analysis. Regular use of the last command, combined with other system monitoring tools, provides comprehensive visibility into system access patterns and helps maintain secure, well-managed computing environments.

By implementing the practices and techniques outlined in this guide, administrators can leverage the full potential of the last command to enhance system security, improve troubleshooting capabilities, and maintain detailed audit trails for their systems.

Tags

  • System Monitoring
  • linux-commands
  • security auditing
  • user sessions
  • wtmp logs

Related Articles

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

The `last` Command: Complete Guide to Linux Login History