The last command in Linux: login history

Introduction

In the management of Linux systems, know who has access to a machine and when it is essential for safety audits, problem resolution and compliance. The commandlastoffers a quick and direct way to check the log start history stored in the file/var/log/wtmp. In this article we will see how it works, what options it gives us and how to interpret your output to get valuable information about access to the system.

What is the last command?

The commandlastbelongs to the profit packagebsdutilsand is in charge of reading the connection log that keeps the login demon. Each time a user starts or ends a session, the system writes an entry in/var/log/wtmp. lastprocess these entries and show them in readable format, indicating user name, terminal, IP address or host name, date and time of start and, where appropriate, closing time.

Basic syntax

The simplest way to uselastis to execute it without arguments:

last

This will show all the recorded sessions, from the latest to the oldest. If we want to limit the output to a certain number of lines, we can useheador the option-noflastsame:

last -n 10

It is also possible to consult the history of a specific user by indicating their name after the command:

last juan

Most commonly used options

  • -a: shows the host name or IP address in the last column, facilitating the identification of the source of the connection.
  • -F: shows the full date and time, including seconds, useful when precision is needed.
  • -i: always shows the IP address instead of trying to solve the host name, which prevents delays for DNS queries.
  • -n NUM: limita la salida a NUM líneas, equivalente a usar head -n NUMbut integrated into the command.
  • -p YYYY-MM-DD: muestra las sesiones que estuvieron activas en una fecha específica, permitiendo filtrar por día.
  • -s YYYY-MM-DD: muestra las sesiones desde una fecha de inicio determinada.
  • -u: indica que se debe mostrar el nombre de usuario en formato completo, útil cuando se tienen cuentas con nombres largos o similares.

Practical examples

Suppose we want to review the last five system access, including the home IP address:

last -a -n 5

To view all user sessionsmariawe can combine-swith today's date:

last maria -s $(date +%Y-%m-%d)

If we need a report of all the failed connections (sessions that did not close correctly) we can observe the lines that end indownorcrashat the exit oflast:

last | grep -E "down|crash"

In environments with multiple network interfaces, it is sometimes useful to force the display of PIs to avoid failed DNS resolutions:

last -i

Finally, to get a quick summary of how many times each user has login in the last week, we can use:

last -s $(date -d "7 days ago" +%Y-%m-%d) | awk '{print $1}' | sort | uniq -c | sort -nr

Interpretation of the exit

Each line of the output oflastcontains the following fields, separated by spaces:

  • User name.
  • Terminal (e.g.pts/0for an SSH connection ortty1for a local console).
  • IP address or host name (depending on the options used).
  • Date and time of the session.
  • Date and time of end or wordstill logged inif the session is still active.
  • Session time (in hours and minutes).

If the session ended unexpectedly, the completion field can showdown, crashorshutdown. These indicators are valuable for detecting possible stability problems or intrusion attempts.

Security considerations

The file/var/log/wtmpis accessible only by root user or group membersadmin many distributions. So, runlastwithout privileges is usually limited to showing only the user's own entries. For complete audits it is necessary to raise privileges withsudo. In addition, it is recommended to rotate and protect this record, as it contains sensitive information about who and from where the system is accessed. On servers exposed to the Internet, combinelastwith tools likefail2banorauditdhelps correlate failed attempts with successful accesses.

Alternatives and supplements

  • lastb: shows failed login attempts reading/var/log/btmp.
  • utmpdump: allows the content of/var/run/utmpwhich contains the meetings currently active.
  • wandwho: offer a summary view of users connected in real time.
  • ICES solutions or centralized registration systems (e.g. Elastic Stack) can indexewtmpfor advanced searches and alerts.

Conclusion

The commandlastis an essential tool for any Linux administrator who needs to review the login history quickly and without complex settings. With its various options it allows to adapt the output to specific needs, from simple consultations of recent access to detailed forensic analysis. Combined with good log management practices and security measures,lasthelps to maintain visibility and control over who access our systems.

This work is under aCreative Commons License Attribution 4.0 International for Francesc Roig francesc @ vivaldi.net.

EnglishenEnglishEnglish