Motd linux ��� ���

Motd linux ��� ���

The actual motd is generated and printed by pam_motd, see its manpage. pam_motd is called twice from /etc/pam.d/login and /etc/pam.d/sshd: Once to print the contents from /run/motd.dynamic and once to print the static (and user editable) content from /etc/motd and /etc/motd.d.

/run/motd.dynamic is updated by pam_motd by executing all executable files from /etc/update-motd.d (via run-parts, see also #931185). If you want additional dynamic information in your motd, /etc/update-motd.d is the place to put your scripts. This is a Debian- and Ubuntu-specific patch that might not be present in other flavours of GNU/Linux distributions and is not factored into upstream PAM. Ubuntu has a man page for a no longer existing update-motd executable which describes what pam_motd does in current versions of Debian.

This code has had security issues in the past (CVE-2010-0832, CVE-2011-3628). No Debian version that is currently under official support is affected by those issues.

For your information, this C code is currently used to execute /etc/update-motd.d

sshd has its own option «?PrintMotd» in /etc/ssh/sshd_config. This defaults to «yes», but is set to «no» in Debian’s default configuration since you get the motd twice otherwise: Once printed by pam_motd, the second time by sshd itself. Please note that the motd doesn’t show on multiplexed ssh connections, only on the «first» session that also does the authentication.

What others do

Ubuntu

Since Ubuntu Intrepid Ibex (2008.10), Ubuntu handles the motd the same way as Debian does it since Debian 8 (jessie, EOL 2018). Is it therefore basically compatible.

By default Ubuntu ships with a set of scripts that add the number of packages to be update (for example).

Gentoo

Gentoo doesn’t display the motd file by default, but this can be enabled in login.defs (see this Gentoo wiki page).

According to this Arch wiki page, Arch doesn’t seem to do anything special to /etc/motd other than display it on boot.

CentOS

2019/06: CentOS install pam_motd, but doesn’t use it. sshd is in default configuration and therefore prints the motd on login automatically.

Fedora

2019/06: Uses pam_motd

FreeBSD

In FreeBSD, the motd file is also generated through a boot script, which will preserve modifications by changing only the line that matches (loosely) the uname that gets updated on reboots. The magic lines:

Historic information: /etc/motd in Debian 6 (squeeze, EOL 2014) and before

Debian used to have a peculiar way of handling /etc/motd. The motd was updated at every reboot, in a boot script ( /etc/init.d/bootmisc.sh in lenny and below, /etc/init.d/bootlogs in squeeze), which basically ran the following:

Читайте также:  Понятие файловой системы linux

Since /etc/motd was a symlink to /var/run/motd in Debian, this worked.

Then the pam_motd based method came around, and for a short while, evaluation of /etc/update-motd.d was done by the update-motd pacakge every 10 minutes instead of on-demand via pam_motd.

How to update your /etc/motd

Since /etc/motd basically got overwritten at every reboot, you needed to instead update /etc/motd.tail and either reboot (!!) or also edit /etc/motd.tail or run the above commands. There was a bug report (437176) to provide an easier command to allow you to update only /etc/motd.tail.

How to keep your /etc/motd from being overwritten

This way, /etc/motd would not have been a symlink to the updated one anymore and woul have therefore always stayed the same. The downside to this was that you did not see the latest kernel version in the motd.

Old school «don’t touch my motd» approach

Similar to the above, this approach also made sure dynamic information could be displayed.

Who was responsible for /etc/motd?

Here’s a list of packages which did that work:

base-files basically took care of installing the motd on boot but did not replace it on upgrade (see /usr/share/doc/base-files/README)

Источник

Create a Custom MOTD or Login Banner in Linux

Back in the old days, before graphical interfaces, system administrators would leave a message for users by using the Message of the Day “MOTD” file. These days the motd still exists but is rarely ever used. I personally haven’t seen someone use the motd file since 2011, when Bob the Unix admin retired at the age of 71. He was still sharp as a tack, but I digress. The motd option is still available in most modern Linux systems. In this fun article we will show you how to set the motd and even create a nice custom login banner with ascii art and system information.

Setting a Basic Text MOTD in Linux

You can easily set a basic text based message of the day by editing the /etc/motd file. Any text that you place in the file will be displayed upon login by any user.

Now when someone logs in via the terminal or ssh they will see the message.

This should work on any Unix or Linux machine regardless of distro. I have tested it on Ubuntu 18.04.2, Fedora 30, CentOS 7 and Red Hat 8.

Custom Login Script in Etc Profile

Another, more flexible, option is to create a script and place it in the /etc/profile.d/ folder. Any script in this folder will run when a user logs in.

Using a script in /etc/profile.d allows you almost limitless possibilities. I used an ascii art generator to create my server name, then added some color to it, and made this nifty little login banner. I later added the lastlog and uptime commands to show me some information about the server.

Here is an example of the script I made running when I log into my server named Fenrir.

How to Make Ascii Art Login Banner

If you are interested in making something like the above, follow these steps.

Use an online ascii art generator to create your desired art and copy all of the characters to the clipboard. Create a file and paste in the characters copied above and save the file.

Читайте также:  Как принудительно обновить драйвер windows

Now run the following command and replace filename with the name of the file you created in the previous step. This will generate your login script.

Now copy mymotd.sh to /etc/profile.d and make it executable.

Now when you log in, you will see the banner in your terminal. You can modify this file anyway you like.

Using neofetch To Create a Custom Login Banner

The neofetch utility is a command line tool that displays the distribution logo and system information for whatever system it is installed on. You can use this as a neat way to create a custom login banner.

Installing neofetch Utility

You can install neofetch easily with most package managers.

To install neofetch on Fedora:

To install neofetch on Ubuntu:

Using neofetch

Although neofetch has a ton of options, you only need to invoke it without any arguments to get a nice looking ascii logo and some system information (as seen above).

To use neofetch as your login banner simply run the following command to create a script that runs at login.

The Ubuntu/Debian Specify Method

Ubuntu and Debian users can use a method that is specific to these distributions. Ubuntu uses scripts in the /etc/update-motd.d directory to show you information when you login by default. Here is a screenshot from a fresh Ubuntu 18 install.

You can edit or add a file to the /etc/update-motd.d folder to run different scripts. To create a custom login banner or motd you can simply use the techniques above and place your scripts here. Each script starts with a double digit number that determines the run order. For example 00 runs first, 99 runs last.

Conclusion

Creating a custom login banner or motd is a lot of fun and looks pretty cool. You can also use it the old fashioned way to show users important information they need to know. Bob the Unix admin used the motd to tell people when the system would be down for maintenance or to scold users who did something he didn’t approve of.

I hope I covered everything in this article. If you have any questions or comments you can leave them below. Have fun!

Источник

Вики IT-KB

Пошаговые руководства, шпаргалки, полезные ссылки.

Инструменты пользователя

Инструменты сайта

Боковая панель

Настраиваем динамический motd в Debian GNU/Linux 8

После регистрации пользователя в Linux-системе, как правило, отображается так называемое «сообщение дня» — message of the day или сокращённо motd. В Debian GNU/Linux 8 (Jessie) это сообщение имеет «грустный» вид.

Попробуем сделать это сообщение информативней и полезней для администратора. Создадим специальный каталог, который будет содержать наши скрипты, которые будут использоваться для генерации динамического motd.

Создадим в этом каталоге файл скрипта и сделаем его исполняемым:

Отредактируем наш скрипт:

Наполним файл скрипта содержимым «по вкусу». Например я взял вариант из проекта riespandi — Dynamic SSH Banner и немного его подправил под свои нужды. В итоге получилось примерно следующее:

Сохраним скрипт, удалим статический motd-файл и вместо него создадим символическую ссылку на файл /var/run/motd, который будет обновляться при каждом входе в систему нами скриптом.

После проделанных изменений войдём в систему локально или через SSH и проверим результат:

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

За вызов механизма обновления motd при входе в систему отвечают настройки в файлах политик PAM. Например в файле nano /etc/pam.d/sshd за это отвечают 2 строчки вызова библиотеки pam_motd.so

Читайте также:  Линукс время изменения файла

Дополнительные источники информации:

Автор первичной редакции:
Алексей Максимов
Время публикации: 15.03.2017 10:00

Источник

Заметки про motd

motd — message of the day, сообщение отображаемое при входе в Linux-систему (на примере Ubuntu).

Раньше файл, содержащий приветствие располагался в /etc/motd , сейчас же это набор скриптов, располагающихся в каталоге /etc/update-motd.d/ :

Порядок отображения, как правило, в порядке заданных приоритетов — 00, 10 и тп…

В результате выполнения отображается:

Много лишнего для нас — не так ли?

Я отключу часть и добавлю своё приветствие.

Создам файл и сделаю его исполняемым.

Теперь открываю его в любом редакторе и добавляю:

Где -e — включить поддержку вывода Escape последовательностей, \033[34m и \033[33m — цвета текста, \033[0m — сброс цветов.

Доступны такие цвета текста:
\033[30m — чёрный;
\033[31m — красный;
\033[32m — зелёный;
\033[33m — желтый;
\033[34m — синий;
\033[35m — фиолетовый;
\033[36m — голубой;
\033[37m — серый.

И такие цвета фона:

\033[40m — чёрный;
\033[41m — красный;
\033[42m — зелёный;
\033[43m — желтый;
\033[44m — синий;
\033[45m — фиолетовый;
\033[46m — голубой;
\033[47m — серый;
\033[0m — сбросить все до значений по умолчанию.

Просмотреть результат можно командой sudo run-parts /etc/update-motd.d или cat /var/run/motd.dynamic .

00-header — содержит само приветствие Welcome to Ubuntu 18.04.5 LTS (GNU/Linux 4.15.0-118-generic x86_64)
10-help-text — ссылки на информацию и сапппорт
50-landscape-sysinfo ведет к сприпту для получения системной информации
50-motd-news — какие-то новости
80-livepatch — информация про Livepatch
80-esm — информация об Extended Security Maintenance — Расширенное обслуживание системы безопасности
Далее скрипты об обновлениях, перезагрузке и тд.

Для отключения ненужных сообщений просто задаю им права 400 .

Источник

Вики IT-KB

Пошаговые руководства, шпаргалки, полезные ссылки.

Инструменты пользователя

Инструменты сайта

Боковая панель

Настраиваем динамический motd в Debian GNU/Linux 9 (Stretch)

После регистрации пользователя в Linux-системе, как правило, отображается так называемое «сообщение дня» — message of the day или сокращённо motd.

В Debian GNU/Linux 9 (Stretch) это сообщение имеет малоинформативный вид.

Попробуем сделать это сообщение информативней и полезней для администратора. Скрипт, которые будут использоваться для генерации динамического motd будем размещать в каталоге /etc/update-motd.d , который существует в конфигурации по умолчанию в Debian Stretch.

Создадим в этом каталоге файл скрипта и сделаем его исполняемым:

Отключим содержащийся по умолчанию в этом каталоге скрипт 10-uname , сняв с него признак исполняемого

Отредактируем наш скрипт:

Наполним файл скрипта содержимым «по вкусу». Мой пример будет выглядеть следующим образом:

Сохраним скрипт, удалим статический motd-файл и вместо него создадим символическую ссылку на файл /var/run/motd, который будет обновляться при каждом входе в систему нами скриптом.

После проделанных изменений войдём в систему локально или через SSH и проверим результат:

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

За вызов механизма обновления motd при входе в систему отвечают настройки в файлах политик PAM. Например в файле nano /etc/pam.d/sshd за это отвечают 2 строчки вызова библиотеки pam_motd.so

Дополнительные источники информации:

Проверено на следующих конфигурациях:

Версия ОС
Debian GNU/Linux Stretch 9.2.1

Автор первичной редакции:
Алексей Максимов
Время публикации: 24.11.2017 19:33

Обсуждение

скажите а как добавить инфу о сетевом трафике вх и исх?

наподобии тот что ниже, но как его вставить в ваш motd.

# 20-network — generate the network information

Источник

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