Linux command last command

Команда last в Linux

Если вы управляете многопользовательской системой, вам часто нужно знать, кто, когда и откуда вошел в систему.

last — это утилита командной строки, которая отображает информацию о последних сеансах входа в систему пользователей системы. Это очень полезно, когда вам нужно отслеживать активность пользователей или расследовать возможное нарушение безопасности.

В этой статье объясняется, как проверить, кто вошел в систему с помощью last команды.

Как использовать last команду

Синтаксис last команды следующий:

Каждый раз, когда пользователь входит в систему, запись для этого сеанса записывается в файл /var/log/wtmp . last читает файл wtmp и печатает информацию о логинах и выходах пользователей. Записи печатаются в обратном временном порядке, начиная с самых последних.

Когда last вызывается без какой-либо опции или аргумента, вывод выглядит примерно так:

Каждая строка вывода содержит следующие столбцы слева направо:

  • Имя пользователя. Когда система перезагружается или выключается, last показывает reboot и shutdown специальных пользователей.
  • Терминал, на котором состоялся сеанс. :0 обычно означает, что пользователь входил в среду рабочего стола.
  • IP-адрес или имя хоста, с которого пользователь вошел в систему.
  • Время начала и окончания сеанса.
  • Продолжительность сеанса. Если сеанс все еще активен или пользователь не вышел из системы, последний будет отображать информацию об этом вместо продолжительности.

Чтобы ограничить вывод определенным пользователем или tty, передайте имя пользователя или tty в качестве аргумента last команды:

Вы также можете указать несколько имен пользователей и ttys в качестве аргументов:

last параметры команды

last принимает несколько параметров, которые позволяют ограничивать, форматировать и фильтровать вывод. В этом разделе мы рассмотрим наиболее распространенные.

Чтобы указать количество строк, которые вы хотите напечатать в командной строке, передайте число, которому предшествует один дефис, в last . Например, чтобы распечатать только последние десять сеансов входа в систему, введите:

С помощью опции -p ( —present ) вы можете узнать, кто вошел в систему в определенный день.

Используйте —since -s ( —since ) и -t ( —until ), чтобы указать last отображать строки с или до указанного времени. Эти две опции часто используются вместе для определения временного интервала, в течение которого вы хотите получить информацию. Например, чтобы отобразить записи входа с 13 по 18 февраля, вы должны запустить:

Время, передаваемое параметрам -p , -s и -t , можно указать в следующих форматах:

По умолчанию в last не отображаются секунды и год. Используйте параметр -F , —fulltimes чтобы просмотреть полное время и даты входа и выхода:

Опция -i ( —ip ) заставляет last всегда показывать IP-адрес, а —dns -d ( —dns ) показывает —dns хостов:

Выводы

last команда выводит информацию о времени входа и выхода пользователей. Для получения дополнительной информации о команде введите в терминале man last .

Если у вас есть вопросы, оставьте комментарий ниже.

Источник

Linux / Unix: last Command Examples

I am a new Linux and Unix system user. How can I find out last logins of users and ttys on Linux/Unix-like operating systems?

You need to use the last command to show who has recently used the server and logged in and out date/time.[donotprint]

Читайте также:  Виртуальный сервер операционная система windows
last command details
Description Show last logged in users.
Category N/A
Difficulty Easy
Root privileges No
Est. reading time 5m
Table of contents
  • » Syntax
  • » Examples
  • » List all users last logged in/out time
  • » List a a particular user last logged in
  • » Hide hotnames
  • » Display complete login & logout times
  • » Display full user/domain names
  • » Display last reboot time
  • » Display last shutdown time
  • » Find out particular logged in time
  • » Video tutorials
  • » See also

Purpose

To find out when a particular user last logged in to the Linux or Unix server.

Syntax

The basic syntax is:

last
last [userNameHere] last [tty] last [options] [userNameHere]

If no options provided last command displays a list of all users logged in (and out) since /var/log/wtmp file was created. You can filter out results by supplying names of users and tty’s to show only those entries matching the username/tty.

last command examples

To find out who has recently logged in and out on your server, type:
$ last
Sample outputs:

You can specifies a file to search other than /var/log/wtmp using -f option. For example, search /nas/server/webserver/.log/wtmp:
$ last -f /nas/server/webserver/.log/wtmp
last -f /nas/server/webserver/.log/wtmp userNameHere

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

List all users last logged in/out time

last command searches back through the file /var/log/wtmp file and the output may go back to several months. Just use the less command or more command as follows to display output one screen at a time:
$ last | more
last | less

List a particular user last logged in

To find out when user vivek last logged in, type:
$ last vivek
$ last vivek | less
$ last vivek | grep ‘Thu Jan 23’
Sample outputs:

Fig. 01 Displaying out when user vivek last logged in on server

Hide hotnames (Linux only)

To hide the display of the hostname field pass -R option:
$ last -R
last -R vivek
Sample outputs:

Display complete login & logout times

By deault year is now displayed by last command. You can force last command to display full login and logout times and dates by passing -F option:
$ last -F
Sample outputs:

Display full user/domain names

Display last reboot time

The user reboot logs in each time the system is rebooted. Thus following command will show a log of all reboots since the log file was created:
$ last reboot
$ last -x reboot
Sample outputs:

Display last shutdown time

Find out the system shutdown entries and run level changes:
$ last -x
$ last -x shutdown
Sample outputs:

Find out who was logged in at a particular time

The syntax is as follows to see the state of logins as of the specified time:
$ last -t YYYYMMDDHHMMSS
$ last -t YYYYMMDDHHMMSS userNameHere

This tutorial is also available in a quick video format:

See also
  • /var/log/wtmp file.
  • last(1) Linux/Unix command man page

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

who was logged in at a particular time

who was logged in at a particular time is not working.
rather than all are very simple greate command

Unfortunately the ‘last’ command is not always accurate, listing multiple ‘still running’ records:
boot 2016-09-27T07:32:33+1000 still running
boot 2016-09-26T18:17:55+1000 still running
boot 2016-09-25T14:09:07+1000 still running
boot 2016-09-25T10:24:46+1000 – 2016-09-25T14:08:20+1000 (03:43)
boot 2016-09-25T08:40:03+1000 – 2016-09-25T10:24:08+1000 (01:44)

user tty7 :0 Mon Oct 3 18:24 – down (04:52)
user tty7 :0 Mon Oct 3 15:21 – 18:24 (03:02)
reboot system boot 4.4.0-38-generic Mon Oct 3 15:19 – 23:16 (07:56)

I wasn’t in my home before 18:30 or 18:20 (I don’t remember exactly the time that I had arrived).

reboot system boot 4.4.0-21-generic Tue Oct 4 23:14 still running
user tty7 :0 Tue Oct 4 19:06 – crash (04:08)

Today is October 5th, then why my computer is “still running” if I had shutdown it yesterday and when I arrived today it was shutdown?

Can anyone help me understand this?

What is difference between “last” & “who”?

The who command show who is logged on right now. last command show a listing of last logged in and logged out users since /var/log/wtmp was created.

Источник

Linux Last Command with Examples

Linux last command is used to check previously logged in user into your server. This command is very important in Linux as it helps for the audit trail. Assume that something is changed in the Linux system, in this situation you are not sure who has made the changes. Using the ‘last’ command you can identify who logged in at a particular time.

Last command displays a list of all user logged in and out from ‘/var/log/wtmp’ since the file was created. Wtmp is a log file that captures and records every login and logout event. This is a binary file that cannot view by any text editors. This trick is pretty smart because any user or root can not modify the file as they want.

Last command gives you information about the name of all users logged in, tty, IP Address (if the user doing a remote connection) date/time, and how long the user logged in.

How to run Last command

You just need to type ‘last’ on your console.

Here’s the sample:

Here’s how to read last information:

The first column — name of the user who has logged in.

The second column — give us information about how the user is connected ( via pts or tty). Exception for reboot activity the status will be shown as ‘system boot’.

The third column — shows where the user connected from. If the user connect from remote computer, you will see a hostname or an IP Address. If you see :0.0 or nothing it means that the user is connect via local terminal. Exception for reboot activity, the kernel version will be shown as the status.

The remaining columns — displays login time and data stamp when the log activity has happened. Numbers in the bracket tell us how many hours and minutes the connection was happened.

pts (pseudo terminal) — means that the user connect via remote connections such as SSH or telnet.
tty (teletypewriter) — means that the user connect via direct connection to the computer or local terminal.

1. Limit number of lines

When you have a lot of lines to show, you can limit how many lines do you want to see using -n option.

In the following command it will display 3 lines starting from the current time and backwards.

2. Hide hostname/IP Address

Use -R option to hide hostname or ip address from printing.

3. Display hostname in last column

Sometimes it’s easy to print hostname or ip address at the last column. To do this, you can use -a option as shown below:

4. Print full login and logout time and dates

By default, last command won’t show full date and time. You can use -F option for this.

5. Search between specific dates

You can use -s (since) and -t (until) options to search logs between specific dates.

For example, the following command will print logs from 1st February to 1st May 2019.

6. Print specific user name

If you want to trace specific user, you can print it specifically. Put the name of user with last command.

Or if you want to know when reboot is done, you can also display it

7. Print specific tty/pts

Last can also print information about specific tty/pts. Just put the tty name or pty name behind the last command.

When you see down value in brackets, it means that the user was logged in from specific time until the system is reboot or shutdown.

8. Use another file than /var/log/wtmp

By default, last command will parse information from ‘/var/log/wtmp’. If you want the last command parse from another file, you can use -f parameter.

For example, you may rotate the log after a certain condition. Let’s say the previous file is named ‘/var/log/wtmp.1’ .

Then the last command will look as following:

9. Display the run level changes

There is -x option, if you want to display run level changes.

Here’s a sample output:

You can see that there are two entries of run level. Runlevel which has to lvl 3 entry means the system is running on full console mode. No active X Window or GUI. Meanwhile, when the system is shutdown, Linux us run level 0. That’s why last show you to lvl 0 entry.

To display the last shutdown date and time, use the following command:

10. View bad logins

While last command logs successful logins, then lastb command record failed login attempts. You must have root access to run lastb command. Lastb will parse information from /var/log/btmp.

Here’s a sample output from lastb command.

11. Display locahost IP address

With -d option (for non-local logins), linux stores not only the host name of the remote host but also its IP number.

12. Rotate wtmp logs

Since ‘/var/log/wtmp’ record every single log in activities, the size of the file may grow quickly. By default, Linux will rotate ‘/var/log/wtmp’ every month. The detail of rotation activity is put in /etc/logrotate.conf file.

Here’s the content of my ‘/etc/logrotate.conf’ file.

And for ‘/var/log/btmp’, here’s default configuration of rotate activity

Clear last command history

As we know that it writes to wtmp, so if we want to delete last history, then we can do it via

Conclusion

In this tutorial, we learned how to use last command in Linux to check logs from wtmp file. For more detail, please visit last manual page by typing man last on your console.

Источник

Читайте также:  8oot logo changer для windows
Оцените статью