- Linux: SSH Session Logging
- How to log SSH session output in Linux?
- Introduction
- Tee Linux Command
- Example
- Conclusion
- Terminal Logs :- Monitor User’s Terminal Activity Using ” tlog ” in Linux
- Install tlog utility on Linux
- Real Time Log Monitoring for Apache or PHP
- Лог файлы Linux по порядку
- Основные лог файлы
- И другие журналы
- Чем просматривать — lnav
Linux: SSH Session Logging
Objective: Log the output of a ssh session on Linux.
The OpenSSH SSH client installed by default on most Linux distributions does not support session logging. By default, we usually use the following ssh command syntax to connect to a server.
In order to log the ssh session output, we will need to read the output from the ssh session and redirect the output to both the screen and to a file. The best tool for this job is tee – a small utility that reads data from standard input and writes it to both standard output and one or more files, effectively duplicating its input. So, to enable ssh session logging, we will need to use the following command syntax where the ssh command output is redirected to tee .
The tee command will output the ssh session log to both the screen and to a file. In the example above, the ssh session log will be written to /path/to/ssh/logfile.log file.
Another alternative is to use the screen command to log ssh sessions.
Start a new screen session.
Once you are in the screen terminal, use Ctrl-a : key sequence to enter screen command line mode. At the prompt, specify the screen log file name. This step is optional.
Next, use Ctrl-a H key sequence to enable logging. If you did not specify the log file name in the above step, log files will be named screenlog.n by default, where n is the screen window number. Once logging is enabled, use ssh as normal within the screen terminal.
Once you are done, exit the ssh session and use Ctrl-a H key sequence again to end screen logging.
How to log SSH session output in Linux?
Introduction
In this article we will see how it is possible to log SSH or telnet session output to a file. I usually use this method for saving the configuration of remote network devices like routers or switches, but it might be useful in any other situations when you need to save all session output to a text file.
Tee Linux Command
Tee is a Linux utility which reads from standard input and writes to both standard output and a file. In other words, instead of sending something directly to standard output (your terminal) you can send stream to tee and it will forward your stream to standard output and send a copy to the file.
When you log into a remote device using SSH/telnet you get a stream which is sent to your standard output (terminal), so you can interact with the remote device. Now if you pipe that output to tee it will still give you a copy of that stream (standard output) and at the same time write that output to the specified file.
Example
Now I will connect to my firewall and log the output:
The log.txt file contains the same output log:
You can use -a option if you want to append the output to the file instead of overwriting it, which is the default behavior:
Conclusion
Now you know how to use tee command for logging session output. Thank you for reading.
Terminal Logs :- Monitor User’s Terminal Activity Using ” tlog ” in Linux
Guys, may be there are lots of reason to monitor user terminal activity like what command user is executing or running may be its for privacy reason. It may be compliance reason or just for good in practice for System Administrator.
Sometime just you want to what users are doing using terminal. So it will help to build trust on users. For all this you can use tlog. it is a terminal I/O logger which comes in *NIX and other distributions.
In this article I will explain some basic tlog configuration. As you now we can monitor who logged in or failed during ssh login. But it is very default to monitor every terminal activity of unprivileged user. May be user can delete the terminal history.
So here we can use tlog Linux utility tools to monitor all user’s terminal activity. tlog also keep logs in JSON format as well so that we can parsed or even we can use it latter.
Let’s start First we need to install tlog utility:
Install tlog utility on Linux
Run the below command to install tlog utility on system.
Next, create a group and add the user in this group, in my example I am creating a suspicious-users group and I will add the users here. We can also log individual user as well.
Now modify the the below configuration file to add the group.
/etc/sssd/conf.d/sssd-session-recording.conf . Make sure that this file is owned by root:root, and users/others cannot read or write the file for security reason.
After updating this file restart sssd.
Now let’s log user sessions.
Suppose Jack user looks suspicious than add this user in suspicious-users group.
Whenever user logged in it will prompt that you are being watched. You can modified or remove this bu using the notice directive in /etc/tlog/tlog-rec-session.conf . So here we can notify user that your terminal session are being monitored and use command carefully.
You can use Cookpit for GUI it is best tool to view the logs. If you’re not using Cockpit, viewing the logs gets a little more complicated, as the data you’re looking for is in the system journal. In this case, I found it easiest to just switch tlog over to recording to a file. You could also log to syslog, which would have a similar effect and perhaps be easier to maintain. For the sake of simplicity, I’m just going to write directly to a file. I should warn you that moving tlog logs out of the system journal and into a file breaks the Cockpit integration.
First, create a place to store the files, and make sure it’s writable by the tlog user. I added a directory in /var/log called tlog and set the ownership to tlog:tlog.
Next, in /etc/tlog/tlog-rec-session.conf , tell tlog where to store its logs. You’ll find stanzas in the file for different configurations. One is labeled File writer parameters. This parameter allows you to define the path for the output file. The configuration for my path looked like this:
Now tell tlog to use the file writer instead of the default, which is the journal. At the bottom of the config file, you’ll find a line just before the closing > that contains a //”writer”: “journal” setting. Change that setting to file, like so:
The next time your target user logs in, the file /var/log/tlog/tlog.log should be created, and sessions logged there. You’ll want to set up log rotation on this, and if you have an external logger, you should send this file there. This data is only useful if it’s available when you need it. If an attacker finds it and deletes it, it won’t do you any good.
If you would like to see your php or Apache web server log in real time. You will need to use tail command which print last part of file in real time including all incoming logs to a standard output device like screen.
If you want to monitory your Apache or PHP logs in Real time this below steps will help you.
Real Time Log Monitoring for Apache or PHP
Tail is useful to :
1. To show log files in real time.
2. Debug and troubleshoot servers problem.
3. Troubleshoot security issue.
4. Also monitor spammers, IP Address, Scripts etc..
Tail basic command syntax:
For example: If your log file name is /var/log/httpd/access.log, type below command:
If your php fpm error log file name is /var/log/php-fpm/error.log, type below command:
You will get some output like below:
By default tail print last 10 line of a file.
Лог файлы Linux по порядку
Невозможно представить себе пользователя и администратора сервера, или даже рабочей станции на основе Linux, который никогда не читал лог файлы. Операционная система и работающие приложения постоянно создают различные типы сообщений, которые регистрируются в различных файлах журналов. Умение определить нужный файл журнала и что искать в нем поможет существенно сэкономить время и быстрее устранить ошибку.
Журналирование является основным источником информации о работе системы и ее ошибках. В этом кратком руководстве рассмотрим основные аспекты журналирования операционной системы, структуру каталогов, программы для чтения и обзора логов.
Основные лог файлы
Все файлы журналов, можно отнести к одной из следующих категорий:
Большинство же лог файлов содержится в директории /var/log .
- /var/log/syslog или /var/log/messages содержит глобальный системный журнал, в котором пишутся сообщения с момента запуска системы, от ядра Linux, различных служб, обнаруженных устройствах, сетевых интерфейсов и много другого.
- /var/log/auth.log или /var/log/secure — информация об авторизации пользователей, включая удачные и неудачные попытки входа в систему, а также задействованные механизмы аутентификации.
- /var/log/dmesg — драйвера устройств. Одноименной командой можно просмотреть вывод содержимого файла. Размер журнала ограничен, когда файл достигнет своего предела, старые сообщения будут перезаписаны более новыми. Задав ключ —level= можно отфильтровать вывод по критерию значимости.
- /var/log/alternatives.log — Вывод программы update-alternatives , в котором находятся символические ссылки на команды или библиотеки по умолчанию.
- /var/log/anaconda.log — Записи, зарегистрированные во время установки системы.
- /var/log/audit — Записи, созданные службой аудита auditd .
- /var/log/boot.log — Информация, которая пишется при загрузке операционной системы.
- /var/log/cron — Отчет службы crond об исполняемых командах и сообщения от самих команд.
- /var/log/cups — Все, что связано с печатью и принтерами.
- /var/log/faillog — Неудачные попытки входа в систему. Очень полезно при проверке угроз в системе безопасности, хакерских атаках, попыток взлома методом перебора. Прочитать содержимое можно с помощью команды faillog .
- var/log/kern.log — Журнал содержит сообщения от ядра и предупреждения, которые могут быть полезны при устранении ошибок пользовательских модулей встроенных в ядро.
- /var/log/maillog/ или /var/log/mail.log — Журнал почтового сервера, используемого на ОС.
- /var/log/pm-powersave.log — Сообщения службы экономии заряда батареи.
- /var/log/samba/ — Логи файлового сервера Samba , который используется для доступа к общим папкам Windows и предоставления доступа пользователям Windows к общим папкам Linux.
- /var/log/spooler — Для представителей старой школы, содержит сообщения USENET. Чаще всего бывает пустым и заброшенным.
- /var/log/Xorg.0.log — Логи X сервера. Чаще всего бесполезны, но если в них есть строки начинающиеся с EE, то следует обратить на них внимание.
Для каждого дистрибутива будет отдельный журнал менеджера пакетов.
- /var/log/yum.log — Для программ установленных с помощью Yum в RedHat Linux.
- /var/log/emerge.log — Для ebuild -ов установленных из Portage с помощью emerge в Gentoo Linux.
- /var/log/dpkg.log — Для программ установленных с помощью dpkg в Debian Linux и всем семействе родственных дистрибутивах.
И немного бинарных журналов учета пользовательских сессий.
- /var/log/lastlog — Последняя сессия пользователей. Прочитать можно командой last .
- /var/log/tallylog — Аудит неудачных попыток входа в систему. Вывод на экран с помощью утилиты pam_tally2 .
- /var/log/btmp — Еже один журнал записи неудачных попыток входа в систему. Просто так, на всякий случай, если вы еще не догадались где следует искать следы активности взломщиков.
- /var/log/utmp — Список входов пользователей в систему на данный момент.
- /var/log/wtmp — Еще один журнал записи входа пользователей в систему. Вывод на экран командой utmpdump .
И другие журналы
Так как операционная система, даже такая замечательная как Linux, сама по себе никакой ощутимой пользы не несет в себе, то скорее всего на сервере или рабочей станции будет крутится база данных, веб сервер, разнообразные приложения. Каждое приложения или служба может иметь свой собственный файл или каталог журналов событий и ошибок. Всех их естественно невозможно перечислить, лишь некоторые.
- /var/log/mysql/ — Лог базы данных MySQL.
- /var/log/httpd/ или /var/log/apache2/ — Лог веб сервера Apache, журнал доступа находится в access_log , а ошибки — в error_log .
- /var/log/lighthttpd/ — Лог веб сервера lighttpd.
В домашнем каталоге пользователя могут находится журналы графических приложений, DE.
/.xsession-errors — Вывод stderr графических приложений X11.
/.xfce4-session.verbose-log — Сообщения рабочего стола XFCE4.
Чем просматривать — lnav
Почти все знают об утилите less и команде tail -f . Также для этих целей сгодится редактор vim и файловый менеджер Midnight Commander. У всех есть свои недостатки: less неважно обрабатывает журналы с длинными строками, принимая их за бинарники. Midnight Commander годится только для беглого просмотра, когда нет необходимости искать по сложному шаблону и переходить помногу взад и вперед между совпадениями. Редактор vim понимает и подсвечивает синтаксис множества форматов, но если журнал часто обновляется, то появляются отвлекающие внимания сообщения об изменениях в файле. Впрочем это легко можно обойти с помощью .
Недавно я обнаружил еще одну годную и многообещающую, но слегка еще сыроватую, утилиту — lnav, в расшифровке Log File Navigator.
Установка пакета как обычно одной командой.
Навигатор журналов lnav понимает ряд форматов файлов.
- Access_log веб сервера.
- CUPS page_log
- Syslog
- glog
- dpkg.log
- strace
- Произвольные записи с временными отметками
- gzip, bzip
- Журнал VMWare ESXi/vCenter
Что в данном случае означает понимание форматов файлов? Фокус в том, что lnav больше чем утилита для просмотра текстовых файлов. Программа умеет кое что еще. Можно открывать несколько файлов сразу и переключаться между ними.
Программа умеет напрямую открывать архивный файл.
Показывает гистограмму информативных сообщений, предупреждений и ошибок, если нажать клавишу . Это с моего syslog-а.
Кроме этого поддерживается подсветка синтаксиса, дополнение по табу и разные полезности в статусной строке. К недостаткам можно отнести нестабильность поведения и зависания. Надеюсь lnav будет активно развиваться, очень полезная программа на мой взгляд.