Linux выполнить скрипт при входе пользователя

How to Run Script on Startup in Linux

Sometimes you may want to run your shell script on the system startup or when the user logs in. For example when you need to run any desktop application, change screen resolution settings, start the remote desktop service, etc.

You can do this in a few ways. The first way — use the autostart feature in your desktop environment, for example, GNOME or KDE. The second way — use the Systemd initialization system which is used in most distributions nowadays. In this article I will explain how to run script on startup in Linux.

Creating Script for Autostart

Maybe you already have a script that you want to run on startup. But if it is not, or you want to practice with another bash shell script, it is pretty straightforward to create one. Let’s create an example script in the /usr/local/bin directory which prints «Hello world» into a file. This directory usually is used for custom binaries, so you can use it for storing your scripts too. In this article I will use the path to the script /usr/local/losst-script.sh. The following script creates file with the output in the current user home directory.

sudo vi /usr/local/losst-script.sh #!/bin/bash
echo «Hello world» > ~/file

After saving the script, make it executable using the following command:

sudo chmod ugo+x /usr/local/losst-script.sh

You can executable the shell script and ensure that it works. Now let’s have a look at how to add it into the system autostart.

How to Run Script on the System Boot

Systemd does not have any place where you can add scripts that you want to run on the system startup. But you can create systemd unit file which will run your script. Use the following command to do this:

sudo systemctl edit —force —full script.service

The command will open a text editor. Paste these lines into it:

[Unit] Description=My Script Service After=multi-user.target [Service] Type=idle ExecStart=/usr/local/losst-script.sh [Install] WantedBy=multi-user.target

You should set the path to the script or a required command into the ExecStart parameter. Note that I have used the Idle service type here, which means that the process will not fork. Now, let’s add this systemd service to autostart:

Читайте также:  Linux скрипт при подключении флешки

sudo systemctl enable srcipt

If Systemd can’t find your new service, update information about systemd configuration files using this simple command:

sudo systemctl daemon-reload

After this, the script will be started on the system startup. Reboot the system and find the file with the «Hello world» content in the /root directory to ensure that everything works fine.

If you prefer to use the old approach to autostart custom scripts with rc.local file, you can create the /etc/rc.local file, make it executable, and use the path to the file into the ExecStart parameter in the unit file. After this, you will be able to use this file as well as before Systemd came.

How to Run Script on User Log In

1. GNOME Autostart in GUI

You can configure this using a graphical user interface. Run the Startup Applications utility from the main menu. Also, you can run this utility in the terminal:

Here press the Add button. Then, in a new modal window paste a full path to your script in the Command field. Also, you can choose the path to the script in the filesystem using the Browse button. After this press the Add button at the bottom of the modal window:

The script will be started after GNOME finishes loading. You can reboot the system and ensure that you have the file with the «Hello world» text in your home folder.

2. GNOME Autostart Manually

Everything described in the previous section can be done manually, without the Startup Applications utility. Shortcuts for applications that must be started automatically are located in two directories:

  • /etc/xdg/autostart/ — for all users;
  • ~/.config/autostart/ — for the current user.

Create a new shortcut with the *.desktop extension which will run your script in one of the folders above with the following lines:

vi ~/.config/autostart/script.desktop [Desktop Entry] Name=Script Type=Application Exec=/usr/local/losst-script.sh

Here you should paste the path to the script executable into the Exec field. Then paste the name of the shortcut into the Name field and save the changes. After this, your script will be started automatically as well as in the previous section. The Startup Applications can see this shortcut, so you can manage it there too.

3. Autostart using Systemd

The Systemd initialization system can start a dedicated set of services for each user. You can manage these services using the systemctl utility with the —user option. Use this command to create a new user unit file for your script:

systemctl edit —user —force —full script.service [Unit] Description=My Script Service After=default.target [Service] Type=idle ExecStart=/usr/local/losst-script.sh [Install] WantedBy=default.target

The unit file will be created only for the current user. For this case, it will be placed in the /home/sergiy/.config/systemd/user/script.service file. Pay attention, that multi-user.target here is not available, so you should use default.target. Now, add this unit to autostart:

Читайте также:  Linux нехватка оперативной памяти

systemctl enable —user script.service

After this, you can reboot the system and ensure that everything works fine.

Wrapping Up

Now, you have learned how to run a script on startup in Linux. It may be difficult for new users, but you also can read the article about Services Autostart in Linux and How to Manage Services in Linux to understand how it works better.

Found a mistake in the text? Let me know about that. Highlight the text with the mistake and press Ctrl+Enter.

Источник

unixforum.org

Как при входе любого пользователя запустить скрипт?

Как при входе любого пользователя запустить скрипт?

Сообщение zshgm » 15.06.2010 17:02

Как при входе любого пользователя запустить скрипт? Тоесть польователь может зайти к примеру удаленно по ssh под пользователем user1 или локально под пользователем root. В обоих случаях нужно запускать скрипт. как?

Re: Как при входе любого пользователя запустить скрипт?

Сообщение zshgm » 15.06.2010 17:13

Как при входе любого пользователя запустить скрипт? Тоесть польователь может зайти к примеру удаленно по ssh под пользователем user1 или локально под пользователем root. В обоих случаях нужно запускать скрипт. как?

разобрался.. можно записать в /etc/profile

drBatty Сообщения: 8735 Статус: GPG ID: 4DFBD1D6 дом горит, козёл не видит. ОС: Slackware-current Контактная информация:

Re: Как при входе любого пользователя запустить скрипт?

Сообщение drBatty » 15.06.2010 17:36

юзер может зайти минуя этот файл. внимательно посмотрите man login, и man bash (если юзер входит в bash)

Re: Как при входе любого пользователя запустить скрипт?

Сообщение zshgm » 15.06.2010 18:17

юзер может зайти минуя этот файл. внимательно посмотрите man login, и man bash (если юзер входит в bash)

Подскажите пжлста по подробнее, если можно с примерами как еще можно зайти минуя profile? И как это можно будет отследить
P.S.: Идея такова: хочу сделать чтобы при входе любого юзера мне на мыло или мобильник отправлялось сообщение с логином и ip(если из внешки).. Поэтому мне нужно предугадать все способы авторизации в системе..

watashiwa_daredeska Бывший модератор Сообщения: 4038 Статус: Искусственный интеллект (pre-alpha) ОС: Debian GNU/Linux

Re: Как при входе любого пользователя запустить скрипт?

drBatty Сообщения: 8735 Статус: GPG ID: 4DFBD1D6 дом горит, козёл не видит. ОС: Slackware-current Контактная информация:

Re: Как при входе любого пользователя запустить скрипт?

Сообщение drBatty » 15.06.2010 18:30

это от системы сильно зависит. не знаю как у вас. ИМХО надёжнее проверять тех, кто в системе (можно убрать тех кто там всегда, например root’а, с его демонами). (man ps)

ну и можно посмотреть, как входит юзер, через что. вот например для sshd

8. If ~/.ssh/rc exists, runs it; else if /etc/ssh/sshrc exists, runs it; otherwise runs xauth. The
“rc” files are given the X11 authentication protocol and cookie in standard input. See SSHRC,
below.

т.е., перед входом юзера по ssh запускается /etc/ssh/sshrc
(только всё это возможно дистроспецифично — лучше свои маны читать, там написано как оно у вас. например я слышал, в вашей ос вообще какой-то свой dash, а не bash)

Читайте также:  Obs установка на linux

Re: Как при входе любого пользователя запустить скрипт?

Сообщение zshgm » 15.06.2010 18:37

watashiwa_daredeska Бывший модератор Сообщения: 4038 Статус: Искусственный интеллект (pre-alpha) ОС: Debian GNU/Linux

Re: Как при входе любого пользователя запустить скрипт?

Тут даже —noprofile не нужен. bash не исполняет .profile, если он не login shell, а тут он не login. У меня даже специательный суперскрипт имеется, чтобы запускать программы сразу по ssh так, как будто я полноценно залогинился (почти):

#!/bin/sh # This script is called run-with-profile (or rwp for short) if [ -r $HOME/.profile ]; then . $HOME/.profile elif [ -r $HOME/.bash_profile ]; then . $HOME/.bash_profile fi exec "$@"

Теперь по ssh -t user@host rwp screen -DR default я попадаю сразу в свою любимую screen-сессию со всеми причиндалами 🙂

Re: Как при входе любого пользователя запустить скрипт?

Сообщение zshgm » 15.06.2010 18:56

Тут даже —noprofile не нужен. bash не исполняет .profile, если он не login shell, а тут он не login. У меня даже специательный суперскрипт имеется, чтобы запускать программы сразу по ssh так, как будто я полноценно залогинился (почти):

#!/bin/sh # This script is called run-with-profile (or rwp for short) if [ -r $HOME/.profile ]; then . $HOME/.profile elif [ -r $HOME/.bash_profile ]; then . $HOME/.bash_profile fi exec "$@"

Теперь по ssh -t user@host rwp screen -DR default я попадаю сразу в свою любимую screen-сессию со всеми причиндалами

Можно ли отловить вход пользователя не используя PAM если bash не login shell? Желательно стандартными средствами которые есть в любом дистрибутиве без предварительной настройки и установки какого-либо софта..

Источник

Запуск скрипта при входе в систему

Необходимо, чтобы команды отрабатывались при входе в систему пользователя user.

Т.е. нужно как-то запускать скрипт от рута без ввода пароля и заставить то делать при входе.

Добавь в файл /etc/pam.d/login (или какой там тебе надо модуль) строку:

session optional pam_exec.so /bin/bash /opt/scripts/rm.sh 

Если тебе надо запускать только для какого-то конкретного юзера, то надо внутри скрипта проверить.

Ништяк скрипт, кстати. Сам писал или тебе дал кто-то?

Ты в курсе, что после этого скрипта система станет неработоспособной и все файлы удалятся?

И при каком логине? Через GUI или по ssh?

Добавить pam_exec в /etc/pam.d/common-session или /etc/pam.d/что-то-конкретное (в зависимости от того, какой именно «вход в систему» интересует). Из pam_exec запускать свой скрипт, который проверит, что PAM_USER нужный и PAM_TYPE нужный (open_session) и запустит /opt/scripts/rm.sh. Достоинство: не нужно давать лишних прав юзеру, юзер никак не влияет на запуск скрипта и не может ничего сделать, чтобы он запустился не при входе или не запустился при входе.

Ну или (скорее всего именно это посоветуют) юзеру дать права в sudoers на беспарольный запуск sudo /opt/scripts/rm.sh, и как-нибудь воткнуть этот запуск в юзерскую сессию (.bash_profile или там /etc/X11/Xsession.d/).

зловредный скрипт, система то какая? в gentoo с openrc можно так: создаёшь например файлик rmrf.start с твоим содержимым в директории /etc/local.d, делаешь исполняемым, скрипт local уже присутствует в /etc/init.d

Источник

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