Log user login linux

How to Check Linux Login History

You may want to know who logged on your system and from where. You should also see bad login attempts on your system. Learn how to see login history in Linux.

If you have a Linux server, there is a possibility that you have several users accessing the system. You may want to know who is logged on your system, when a particular user logged to the Linux system. You may also want to know from which IP address your system was accessed.

Even if you don’t have multiple users, someone probably have tried to access your Linux server. Trust me, this may sound weird but it’s a common thing these days for bots to try and access your Linux servers. Don’t believe me? Just check the bad login attempts on your server to see if someone tried to login to your system.

Let me show you how to view the Linux login history so that you are aware of who is accessing your system and from where.

Viewing Linux login history

Linux is very good at keeping logs of everything that goes on your system. Quite naturally, it also stores logs about login and login attempts. The login information is stored in three places:

  • /var/log/wtmp – Logs of last login sessions
  • /var/run/utmp – Logs of the current login sessions
  • /var/log/btmp – Logs of the bad login attempts

Let’s see these things in a bit detail.

1. View history of all logged users

To view the history of all the successful login on your system, simply use the command last.

The output should look like this. As you can see, it lists the user, the IP address from where the user accessed the system, date and time frame of the login. pts/0 means the server was accessed via SSH.

abhi pts/0 202.91.87.115 Wed Mar 13 13:31 still logged in root pts/0 202.91.87.115 Wed Mar 13 13:30 - 13:31 (00:00) servesha pts/0 125.20.97.117 Tue Mar 12 12:07 - 14:25 (02:17) servesha pts/0 209.20.189.152 Tue Mar 5 12:32 - 12:38 (00:06) root pts/0 202.91.87.114 Mon Mar 4 13:35 - 13:47 (00:11) wtmp begins Mon Mar 4 13:35:54 2019

The last line of the output tells you the when was the wtmp log file was created. This is important because if the wtmp file was deleted recently, last command won’t be able to show history of the logins prior to that date.

Читайте также:  Какую линукс выбрать новичку

You may have a huge history of login sessions so it’s better to pipe the output through less command.

2. View login history of a certain user

If you just want to see the login history of a particular user, you can specify the user name with last command.

You’ll see the login information of only the selected user:

last servesha servesha pts/0 125.20.97.117 Tue Mar 12 12:07 - 14:25 (02:17) servesha pts/0 209.20.189.152 Tue Mar 5 12:32 - 12:38 (00:06) wtmp begins Mon Mar 4 13:35:54 2019

3. Display IP addresses in login history instead of hostname

You couldn’t see it in the previous output but by default, last command shows the hostname instead of the IP address of the user. If you are on a sub-network, you’ll probably see only the hostnames.

You can force to display the IP addresses of the previously logged users with the -i option.

4. Display only last N logins

If your system has a good uptime, perhaps your login history would be huge. As I mentioned earlier, you can use the less command or other file viewing commands like head or tail.

Last command gives you the option to display only certain number of login history.

Just replace N with the number you want. You can also combine it with the username.

5. View all the bad login attempts on your Linux server

Now comes the important part: checking the bad login attempts on your server.

You can do that in two ways. You can either use the last command with the btmp log file:

or you can use the lastb command:

Both of these commands will yield the same result. The lastb is actually a link to the last command with the specified file.

root ssh:notty 218.92.0.158 Wed Mar 13 14:34 - 14:34 (00:00) sindesi ssh:notty 59.164.69.10 Wed Mar 13 14:34 - 14:34 (00:00) root ssh:notty 218.92.0.158 Wed Mar 13 14:34 - 14:34 (00:00) sindesi ssh:notty 59.164.69.10 Wed Mar 13 14:34 - 14:34 (00:00) root ssh:notty 218.92.0.158 Wed Mar 13 14:34 - 14:34 (00:00)

Bad logins could be an incorrect password entered by a legitimate user. It could also be a bot trying to brute force your password.

You have to analyze here and see if you recognize the IPs in the log. If there has been too many login attempts from a certain IP with user root, probably someone is trying to attack your system by bruteforcing.

You should deploy Fail2Ban to protect your server in such cases. Fail2Ban will ban such IPs from your server and thus giving your server an extra layer of protection.

I hope this tutorial teach you to view login history in Linux and now you can use this knowledge to better manage and protect your Linux system.

Читайте также:  Android windows linux mac apple

If you liked this article, please share it on social media and subscribe to our newsletter for more Linux related tutorials.

Источник

How to check user login history in Linux?

Linux is one of the most accepted operating systems for multi-user setup. A multi-user operating system means a system that more than one user can access. These systems are mostly used in servers of large organizations, businesses, government, and educational sectors.

Different users access the multi-user operating system, and to monitor users’ activity, it is important to keep an eye on login history. Login history gives useful information about different users who have accessed the machine, such as username, terminal name, IP address, date, and time of logging in. Moreover, login history also helps to identify different issues, especially for troubleshooting.

This write-up is focusing on an approach to check the user login history. Before getting into that, let’s understand how Linux arrange and manage login data:

How Linux store log files?

Linux (Ubuntu) stores login data into three locations:

  • var/log/utmp – It contains information about users who are currently logged in
  • var/log/utmw – It contains the history of all logged-in users
  • var/log/btmp – It keeps all bad login attempts

All of these files stores login information and login attempts as well.

How to check the login history?

To check the login history, use the following command:

It gives information about all the users who logged in successfully. It searches through the “var/log/utmw” file and displays the history of all users who have logged in since creating the file.

The above output shows that the different users connected to the server from a machine with IP “192.168.8.113”, “pts/1” indicate that the server was accessed via SSH.

How to check the login history of a specific user?

To check the login history of a specific user, uses the “last” command with the username of that particular user:

I am checking for “martin”; the command would be:

How to check the specific number of logins?

If numerous people are accessing the server, then the login history would be huge. To trim the number of logins, follow the below-mentioned syntax:

Replace “X” with the number of logins you want to display as standard output:

You can also use it with a specific username:

How to check bad login attempts:

As discussed above that Linux also keeps the information of bad login attempts. To display it, use the command given below:

Observing bad login attempts is very critical for security reasons of the server. You can easily identify an unknown IP address that is probably trying to access the server.

Conclusion:

Linux is the most preferred operating system for servers in many businesses because it is a secure multi-user platform. Many users access a server, and to keep a check on user activity, we need user login information. In this guide, we learned how to examine user login history in Linux. Moreover, we also analyzed how bad attempts can be tackled to secure the server. We used the “last” command, but another tool called “aureport” tracks successful and failed logins.

Читайте также:  Grub gfxpayload linux keep

About the author

Sam U

I am a professional graphics designer with over 6 years of experience. Currently doing research in virtual reality, augmented reality and mixed reality.
I hardly watch movies but love to read tech related books and articles.

Источник

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

Кто и когда входил в Linux. Команда Last

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

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

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

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

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

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

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

yuriy pts/0 181.23.456.189 Sat Mar 23 12:27 still logged in nifnif pts/11 181.45.678.912 Wed Mar 20 05:30 - 05:49 (00:19) nafnaf pts/22 181.45.678.312 Fri Mar 15 00:01 - 02:27 (02:26) nufnuf pts/33 181.45.678.411 Wed Mar 13 11:02 - 11:28 (00:26) . 

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

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

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

Просмотр истории входа в систему. Команда Last

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

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

Команда last username

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

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

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

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

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

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

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

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

Заключение

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

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

Источник

Оцените статью
Adblock
detector