Linux last logged in

Содержание
  1. Linux / Unix: Check Last Time User Logged In On The System
  2. Listing the Last times a user logged in on server
  3. Example: Display Linux user last login
  4. Display a list of recent system use for all users
  5. Просмотр истории входа в Linux. Кто и когда входил в систему
  6. Где хранятся логи входа в систему
  7. Просмотр истории входа в систему
  8. Просмотр истории входа для определенного пользователя
  9. Ограничить количество строк
  10. Просмотр неудачных попыток входа в систему
  11. Заключение
  12. UNIX / Linux List Current Logged In Users
  13. Linux Command To List Current Logged In Users
  14. How to find currently logged in users in Linux
  15. Using w command to list current logged in users under Unix or Linux
  16. Understanding w command outputs
  17. Display all logged in users using who command
  18. Getting help with the whois command
  19. users command
  20. Vieing logged in users with last command
  21. How To Find Last Logged In Users In Linux
  22. 1. Display list of last logged in users in Linux with last command
  23. 1.1. Limit output to specific user
  24. 1.2. Limit output to specific tty or pts
  25. 1.3. Limit output to specific number of lines
  26. 1.4. Show hostname instead of IP address
  27. 1.5. Hide hostname and IP address
  28. 1.6. Show user login records on a specific time
  29. 1.7. Display logged in users within specific time interval
  30. 1.8. Display last logged in users with full date and time
  31. 1.9. Display hostname in the last column
  32. 1.10. View last login records of pseudo user «reboot»
  33. 2. Display failed login attempts using lastb in Linux
  34. 3. Find last logged in users in Linux with lastlog command
  35. 3.1. Display last logged in details of a specific user
  36. 3.2. Display last logged in records before or recent than X days
  37. 3.3. Remove or clear the last login information using lastlog in Linux
  38. Getting help

Linux / Unix: Check Last Time User Logged In On The System

Listing the Last times a user logged in on server

The syntax is as follows:[donotprint]

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 1m

[/donotprint]

  • 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

last [option] [UserNameHere]

Example: Display Linux user last login

To display when a user named ‘vivek’ last logged in to the system, type:
$ last vivek
$ last vivek | less
Sample outputs:

Fig.01: last command in action on my Debian base nas server

Display a list of recent system use for all users

Simply type the last command:
$ last
OR
$ last | less
Sample outputs taken from my RHEL based server:

See also
  • I strongly suggest that you see our last command examples page.
  • Read last(1) command man page.
  • See /var/log/wtmp file.

🐧 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.

Thanks for the article. I tried running ‘last’ on an osx box, and it just returned “wtmp begins Mon Mar 10 10:24” which was the current date/time. Running it again gives the same response, updating the date/time. It looks to me like the last datafile is continuously wiped. Do you know what could be causing that?

How can i print only the day in last ?

A fast and simple way would be using grep. Example:

Источник

Просмотр истории входа в Linux. Кто и когда входил в систему

В данной заметке мы рассмотрим, как узнать, какие пользователи и когда именно входили в систему Linux.

Данная информация обычно нужна системным администраторам для просмотра истории входа в систему на многопользовательском сервере.

Помимо этого, бывает полезно узнать о неудачных попытках входа. Это могут быть боты, но могут быть и попытки взлома вашего сервера.

Где хранятся логи входа в систему

Информация о том, кто входил (залогинивался) или пытался войти в систему, хранится в лог файлах. Для этого используется три лог-файла:
/var/log/btmp — неудачные попытки входа.
/var/run/utmp — кто в данный момент залогинен (текущие сессии).
/var/log/wtmp — список всех сессий входа в систему.

Эти файлы, в отличии от большинства других лог-файлов Linux, имеют бинарный формат. Если вы попробуете просмотреть их командой cat , то на экран будет выведена «каша». Для их просмотра используется команда last .

Просмотр истории входа в систему

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

Выполним команду last :

Как вы можете видеть, выводится таблица с информацией. В ней содержатся имена пользователей, IP-адрес, с которого осуществлялся вход, дата и время входа и продолжительность сессии. Запись вида pts/0 означает, что для входа использовалось SSH соединение (или другое удаленное соединение, например, telnet).

Также выводится информация о включении/выключении системы.

Последняя строка в файле /var/log/wtmp показывает, когда был создан файл.

Просмотр истории входа для определенного пользователя

Чтобы показать информацию о сессиях определенного пользователя, то для команды last необходимо указать имя этого пользователя:

Ограничить количество строк

Иногда лог, который выводит команда last , может быть очень большой. Чтобы ограничить количество выводимых строк, используется опция -n ЧислоСтрок или просто -ЧислоСтрок .

Выведем только десять свежих записей:

Просмотр неудачных попыток входа в систему

Как было сказано выше, записи о неудачных попытках входа в систему хранятся в лог-файле /var/log/btmp .

Команда last по умолчанию выводит информацию из файла /var/log/wtmp . Чтобы вывести информацию из другого файла, используется опция -f ИмяФайла

Выведем записи о неудачных попытках входа (из файла /var/log/btmp ):

Или же можно воспользоваться командой lastb . Команда lastb работает точно также, как и команда last , но выводит информацию из файла /var/log/btmp

Заключение

Мы рассмотрели использование команды last для просмотра информации об истории входа в систему.

Дополнительную информацию по использованию команды last можно получить, выполнив в терминале:

Источник

UNIX / Linux List Current Logged In Users

H ow do I print the user names of users currently logged in to the current UNIX / Linux host / server from a command prompt?

You need to use any one of the following command line tools to list currently logged in users on Linux or Unix-like systems.

Tutorial details
Difficulty level Easy
Root privileges Yes
Requirements w or who command on Linux and Unix
Est. reading time 5m

The following two file keep login records on Linux and Unix-like systems:

  • /var/run/utmp – Keeps and allows us to discover information about who is currently using the system. Please note that there may be more L inux and Unix users currently using the system, because not all programs use utmp logging . In other words, poorly written app, hidden programs, malware, and other bad stuff will not be useful to list logged in users.
  • /var/log/wtmp – Keeps records all logins and logouts.

We simply cannot read these files using cat command/grep command/egrep command as file is in binary database format. Hence, we use the following commands to find currently logged in users in Linux and Unix-like systems.

Linux Command To List Current Logged In Users

  1. w command – Shows information about the users currently on the machine, and their processes.
  2. who command – Display information about users who are currently logged in.
  3. users command – See the login names of the users currently on the system, in sorted order, space separated, on a single line. It reads all information from /var/run/utmp file.

How to find currently logged in users in Linux

Open a terminal (or login into remote server using ssh command) and type the following commands.

Using w command to list current logged in users under Unix or Linux

Open the terminal application and then type the w command:
$ w

Fig.01: w command in action.

Understanding w command outputs

From Fig.01 we see the following for each user:

  • USER – Linux or Unix login name.
  • TTY – The tty name.
  • FROM The remote host or IP address.
  • @Login – Login time.
  • IDEL – Idle time.
  • JCPU – The JCPU time is the time used by all processes attached to the tty. However, it does not include past background jobs, but does include currently running background jobs.
  • PCPU – The PCPU time is the time used by the current process, named in the “what” field.
  • WHAT – The command line of that users current process.

To see info about a user named tom, enter:
$ w tom
Tell w command not print header:
$ w -h
$ w —no-header
We can also ignore current process username by passing the -u or —no-current to the w command:
$ w -u
$ w —no-current
Want to see remote hostname field? Try:
$ w -f
Show IP address instead of hostname for from field:
$ w -i
We can also old style output. In other words old outputs prints blank space for idle times less than one minute:
$ w -o

Display all logged in users using who command

The who command works on all Unix like operating systems such as macOS, *BSD, Linux and so on. The syntax is pretty simple:
# who
Here is what we see:

The who command displays the following information:

  • root – The username
  • pts/0 – Type of the terminal device. In this example, we see pseudoterminal pts/0 used by root user.
  • 2013-03-12 15:10 – User login date and time stamp.
  • (10.1.3.177) – The remote IP address from which the user logged into this server.

We can pass the -a option to who command as follows to see time of last system boot, display dead processes, system login processes, active processes spawned by init/systemd, print current runlevel, print last system clock change, show user’s message status, and list users logged in to Linux or Unix box:
# who -a
Here is output from older Linux system (pre Systemd):

Sample outputs from Systemd based Linux sysetem:

Getting help with the whois command

You can pass the following options to the who command (taken from the who command man page):

  • 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

users command

Open a terminal or login over the ssh session and enter the following users command:
$ users
Output who is currently logged:

Vieing logged in users with last command

Want to see a listing of last logged in users? Use the last command to lookup binary database called /var/log/wtmp and displays a list of all users logged in (and out) since that file was created. For instance see history for user named ‘vivek’:
$ last vivek

Источник

How To Find Last Logged In Users In Linux

In this tutorial, we will see how to find last logged in users in Linux using last , lastb and lastlog commands with examples.

As a Linux system administrator, you should routinely check the login date and time of the users in your Linux server. It gives you some useful details such as how many users are active, how many users are inactive and when do they log in and for how long etc. If some user accounts haven’t been used for a long time, you can simply lock them if they are no longer needed. You can also use the last login dates when auditing your Linux servers and investigate which user could have caused the problem. Fortunately, the GNU/Linux operating system includes the triplet commands namely last , lastb and lastlog to display the recent users’ login dates.

1. Display list of last logged in users in Linux with last command

As the name says, the last command is used to view the last logged in users in Linux and Unix-like systems. It reads through the /var/log/wtmp file and finds all logged in as well as logged out users since that file was created. You can also list the recent login dates of a specific user and even find who rebooted the Linux system with the help of last command.

Please note that your system only logs information in the wtmp file. If this file is not available for any reason, simply create it with touch command like below:

Now let us find out the recent login dates and times with last command.

To show the last logins, their duration and other information in your Linux system, simply run:

Sample output:

List last logged in users in Linux with last command

As you see in the above output, the last command shows the following details of recent logins:

  • Name of the user. If any user is still logged in, it will display that details too.
  • Type of the terminal device (E.g. tty or pts) on which the session took place.
  • Source IP address or hostname from which the user logged in.
  • The login date and time stamp (i.e. the login session start and stop times).
  • The total duration of the session.
  • The last line indicates the date and time of the earliest recorded session in the wtmp log file.

In the above output, you might have noticed that there is a login entry of a special user named reboot . The last command keeps the records of this user each time the computer is booted up.

When we run last command without any options, it will show the entire log output. It has many options to filter, format, and limit output as per your liking. I have included examples for most common options.

1.1. Limit output to specific user

As stated already, the last command lists all recent logins recorded in the wtmp file. If you want to display the recent logins of a specific user (i.e. view all logins by a specific user), for example ostechnix, the command would be:

Sample output:

Display the recent logins of specific user with last command

You can also specify multiple usernames with comma-separated like below:

1.2. Limit output to specific tty or pts

The last command keeps the record of the type of the terminal device (E.g. tty or pts) on which the session took place.

Say for example, the users might have logged to the Linux machine either locally or via ssh. If you want to restrict the output to specific tty , simply run:

Sample output:

Names of ttys can be abbreviated. For instance, you can run last 1 instead of last tty1 .

Similarly, to list only pts sessions’ logins, run:

You can also specify multiple usernames with ttys like below:

1.3. Limit output to specific number of lines

The wtmp log file could have large number of entries. If you want to restrict the output of last command to certain number of lines, use -n flag like below:

The above command will only display the 5 lines in the output:

1.4. Show hostname instead of IP address

By default, last command shows the source IP from which the user logged it. If you want to display hostname instead of IP address, use -d (or —dns ) option:

You can also display full user names and domain names in the output with -w (or —fullnames ) option.

1.5. Hide hostname and IP address

To suppress the hostname or IP field, use -R option.

Sample output:

1.6. Show user login records on a specific time

The -p (or —present ) option is used to find who was logged in at present or at a specified time.

For example, run the following command to list last logged in users at a 8:30 today:

Sample output:

To list who is logged at present (i.e. at the time of running this command, run:

Find logged in users at specific time

1.7. Display logged in users within specific time interval

The last command has two options namely -s ( —since ) and -t ( —until ) to display logged in users within a specific period of time. The -s option is used to display the state of logins since the specified time and the -t option is used to display the state of logins until the specified time.

For example, if you want to display the last logins that took place from 2021-01-07 to 2021-01-11 , the command is:

Sample output:

To view recent logins from yesterday to today, run:

If you want to only list login records since January 07, 2021 to till date, run:

1.8. Display last logged in users with full date and time

The -F ( —fulltimes ) option is used to display the full login and logout date and time in last command’s output.

Sample output:

1.9. Display hostname in the last column

The -a ( —hostlast ) option is used to display the hostname column last to prevent truncation.

1.10. View last login records of pseudo user «reboot»

As I mentioned earlier, the last command keeps the record of a special pseudo users named «reboot» and «shutdown».

To view last login details of «reboot» and «shutdown» users, use the following commands:

2. Display failed login attempts using lastb in Linux

The lastb is same as last command, but it only lists all the bad login attempts. It gets the failed login details from the /var/log/btmp file.

Please note that your system only logs information in the btmp file if it is present. If this file is not available for any reason, simply create it with touch command like below:

Now we can display the failed login attempts using lastb command like below:

Sample output:

Display failed login attempts using lastb command in Linux

The above commands lists all unsuccessful login attempts by all users in the Linux system. It also shows failed login attempts that took place via SSH.

3. Find last logged in users in Linux with lastlog command

The lastlog command shows the most recent login of all users or of a specific user in Linux and Unix-like operating systems. It retrieves the list of last logged in users from /var/log/lastlog file and displays the result in standard output.

To display the most recent login of all users, run:

Sample output:

Find last logged in users in Linux with lastlog command

As you see in the above output, lastlog command displays the last login records of system user accounts as well as other service accounts such as bin , daemon , sys , mail , nobody etc.

The lastlog command prints the login-name, port, source IP address from which the user logged in and the last login date and time. If an user has never logged in, it will print the message ** Never logged in** instead of the port and time in the output.

You might be wondering why there are many service accounts have never logged in. This is because the login shells for these accounts are set to either /sbin/nologin . It is common security practice used to limit direct access to the shell.

3.1. Display last logged in details of a specific user

If you want to display lastlog record of a specified user, for example ostechnix, the command would be:

Sample output:

3.2. Display last logged in records before or recent than X days

The lastlog command can able to display recent login records before than or recent than X days.

For instance, you can get recent login records of all users before than 5 days using -b flag like below:

Similarly, to display login records more recent than 5 days, use -t flag:

3.3. Remove or clear the last login information using lastlog in Linux

If you don’t want the lastlog record of an user, just clear them using -C ( —clear ) flag:

To verify if the log record is cleared, run:

Getting help

For more details, refer the help section of the respective command.

Or go through the man pages of each command:

The last , lastb and lastlog commands comes in rescue to detect suspicious user activities in a Linux system. Finding who is recently logged in (or logged out from) the Linux server, when did they log in and for how long are the important details that will definitely help you at troubleshooting times.

Источник

Читайте также:  Get default gateway linux
Оцените статью