Linux motd как раскрасить

Обновлено: 05.07.2024

Я отредактировал значение по умолчанию /etc/update-motd.d/00-header , добавив немного цвета, чтобы его было легче читать:

Я могу просто запустить эту строку кода в терминале, но когда я редактирую 00-header эту информацию, я получаю управляющие коды, напечатанные в виде открытого текста:

Как вы редактировали файл, особенно непечатаемые символы? В pico я заменил существующую строку коды с первой строкой O кода , который я включил в моем примере. Проблема заключается в том, что анализатор MOTD обрабатывает \e и последующие символы как обычный текст, а не как специальные символы. Из заголовка авторского права связанного файла я вижу, что вы действительно в Ubuntu, поэтому я добавляю соответствующий тег, так как он имеет отношение к ответу (относительно используемой оболочки, см. Мой ответ).

Предполагая, что вы находитесь в Ubuntu - который использует dash для запуска системных скриптов:

Этот файл, /etc/update-motd.d/00-header выполняется /bin/dash (не /bin/bash ), который является довольно минималистичным (и быстрым) -
кажется, он не поддерживает «\ e» в этом месте - вместо этого используйте «\ 033» .

Разница в том, когда расширять escape-коды.

В Debian / Ubuntu motd это настраивается в /etc/pam.d/sshd :

Это означает, что при успешном входе в систему система будет работать примерно так:

где /etc/motd статическая часть (только напечатанная, а не исходная).

Debian 9 / Ubuntu 16.04 :

Для генерации динамической части run-parts используется /etc/update-motd.d каталог:

Для немного более читабельного кода вы можете использовать tput setaf . Обратите внимание, что для сохранения цветов мы должны установить TERM переменную.

сохранить файл как например /etc/update-motd.d/10-uname

и убедитесь, что это исполняемый файл:

Основные цвета пронумерованы:

  • 1 - красный
  • 2 - Зеленый
  • 3 - желтый
  • 4 - синий
  • 5 - пурпурный
  • 6 - голубой
  • 7 - Белый

Bash цветной MOTD

Код выше генерирует:

В зависимости от вашего вкуса вы можете создать более красочный вывод, используя lolcat заголовки figlet . Сгенерированный вывод использует стандартный синтаксис bash:

I would like to have a dynamic motd, but I can't figure out how to do it.

I tried what I found, adding /etc/update-motd.d/00-header , 10-sysinfo , 90-footer , and symlinking to /etc/motd /var/run/motd.dynamic , /run/motd.dynamic , /run/motd or /var/run/motd .

I've got these lines in /etc/pam.d/sshd :

I'm also confused with systemd.

Is there a way to do this? Could someone provide a example with a simple fortune?


293 1 1 gold badge 2 2 silver badges 5 5 bronze badges

3 Answers 3

This has changed over the years:

First there was /etc/motd (static).

Then Ubuntu came up with their own package update-motd based on a script called from cron.

Finally, PAM copied Ubuntu's idea of /etc/update-motd.d/, and therefore Debian and others also have that behaviour.

There is an explanation here

So this is how things are currently: PAM will just read /var/run/motd.dynamic and /etc/motd if it exists (paste from post)

  • /etc/motd – The classic, static file. Does not exist anymore in Ubuntu 16.04 LTS, not even as a symbolic link to /var/run/motd. If it is created, however its contents will be printed too.
  • /var/run/motd – This was used by Ubuntu’s first implementation. It is not used anymore. It is just ignored by PAM.
  • /var/run/motd.dynamic – This is what is shown on login currently. It is updated by /etc/init.d/motd at every boot. It is also updated by PAM by running the scripts in /etc/update-motd.d/, if they exist.
  • /etc/motd.tail – The Ubuntu package used to populate /etc/update-motd.d. One of them would cat the contents of this file so it was easy to add static content. That script does not exist in the package anymore, so the file does not have the intended effect.

The example from the post

I am able to test simple dynamic-motd with fortune example on my Debian Jessie 8.2 host as below and found the issue to be related to a buggy behavior.


непосредственно /etc/motd - обычный текст, если хочется туда запихнуть скрипт, то его фигачат в /etc/profile, либо в /etc/bash.bashrc.


Есть автонастройщик. Кастовать cacafire >> /etc/motd


Вот ты свой куда запихнул?




/usr/sbin/hello - сам скрипт, добавил первой строкой в /etc/bash.bashrc.


так и задумывалось. злобный русский цомпутер на ломаном английском вопрошает юзверя.




Утянул к себе. Сделаю вот так, так православнее:

teamfighter ★ ( 15.04.14 17:22:14 )
Последнее исправление: teamfighter 15.04.14 17:22:45 (всего исправлений: 1)


roman77 ★★★★★ ( 15.04.14 17:23:59 )
Последнее исправление: roman77 15.04.14 17:27:46 (всего исправлений: 4)



The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law.


This is a little guide to display dynamic login messages on a Debian system.

This is one of those things where the internet has plenty of resources, but they are mostly outdated and contradictory. Even typing man motd in Debian is a sad experience.

It is not a difficult thing to do but it can be a big waste of time to sort out the contradictions.

Hopefully, this post will help get the big picture from one single place.

Short history

Ancient times

Time ago, most distributions just printed the contents of /etc/motd upon login.

MOTD stands for message of the day (although it was static), and was put in place at installation time, only to be changed at upgrade time maybe.

Some distributions such as Arch keep operating this way.

Ubuntu came along

Then, Ubuntu Intrepid Ibex (2008) introduced a package update-motd, which consisted of

  • a script called update-motd.
  • an entry in /etc/cron.d calling update-motd every 10 minutes.
  • a folder /etc/update-motd.d

The script runs all the scripts in /etc/update-motd.d using run-parts, then stores all output in /var/run/motd.

/etc/motd was then made into a symbolic link to /var/run/motd

And pam_motd copied it

Then, PAM thought that that was actually a cool idea and copied it from Ubuntu. In modern Linux, PAM is in charge of login authentication.

SSH uses the pam_motd module

Ok, now we have yet another file, /run/motd.dynamic.

We can see that they almost literally copied the code.

Confusing huh? Well it gets worse because over time, Debian and Ubuntu have changed things, like the scripts populated in /etc/update-motd.d and the use of special files.

Files involved

How to then?

Okay, so once we understand why Google confuses us, it is pretty easy to customize our MOTD.

First, make sure to disable /etc/init.d/motd, as it writes to /var/run/motd.dynamic.

In my Raspbian Jessie, for instance it already came disabled. Just in case

Then, just delete current static MOTD, create /etc/update-motd.d folder and place scripts in it.

Scripts are run by run-parts, so they need not have an extension. They must start with digits so they will be run in order.

This is a simple example

Next login we will get

Some ideas

FIGlet

You can use good old FIGlet. It will take your input and create some text based ASCII art.

System info

You can play with lm-sensors to get information such as fan speed or temperature.

Also, you can print any of the typical system info provided by standard tools.

Here is one example output


Termpix

You can get even fancier using tools like termpix. This tool creates ASCII art from pictures, and shows better if we have half block capable fonts available.


This is what I used for the MOTD in NextCloudPi.

landscape-sysinfo

This one is Ubuntu only.

Banner
Boxes

List all different designs with

lolcat

You can spice up your creations with trippy rainbow colors with lolcat


Play with it

No need to risk your system. Test your ideas in a Docker container.

, and the official Ubuntu container.

References

Author: nachoparker

3 Comments

For me the missing part was sshd pam_mot.d, which was not activated on my server so nothing would show whatsoever. Its quite easy to overlook this setting, so if anyone else has trouble actually showing the motd this might be worth a look.

This is a great post. It has cleared up a lot of confusion in regards to the MOTD message usage for debian/raspbian.

I have also stumbled upon the issue of PAM not being enabled on my ssh server settings.
I enabled it and followed the recommendation for using session checks:

sudo vim /etc/ssh/sshd_config
UsePAM yes
PasswordAuthentication no
ChallengeResponseAuthentication no

Читайте также: