Linux запуск при логине

How to run a command at login? [duplicate]

I need it only for my user, not all users on the machine. Also, I need it to run whether I login via the GUI or via SSH to a plain shell terminal. I would even like to know how to do this on machines without a GUI installed. Where would I put the above line to be run as explained?

@EliahKagan Yes, I know that. I’m still looking other post, but those link will be useful to login via GUI.

@Lucio I found plenty of explanations how to do it for GUI or for shell or for all users. None of those are what I need.

1 Answer 1

Adding the command to the end of ~/.profile should do the trick (where ~ represents your home directory).

Not ~/.bashrc , which would make it run again every time a bash shell is started. In contrast, .profile is only run by interactive login shells. See man bash and man sh for more information.

Please note that this will run not just for GUI and SSH logins, but for all logins (or at least all interactive logins), including when you log on in a virtual console.

@Lucio If .bash_profile exists, then it overrides .profile for bash . I don’t think the GUI uses a bash shell, though. I’ll edit this to provide a link to man sh too (though I’m not sure it uses sh / dash either). .profile is universal (and typically, when .bash_profile exists, it’s written so it source s .profile ).

@FrankNocke For GUI only, you can start a script from a .desktop file in ~/.config/autostart/ . Or use the gnome-session-properties GUI.

Источник

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

Необходимо, чтобы команды отрабатывались при входе в систему пользователя 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. Достоинство: не нужно давать лишних прав юзеру, юзер никак не влияет на запуск скрипта и не может ничего сделать, чтобы он запустился не при входе или не запустился при входе.

Читайте также:  Установка linux дисковое пространство

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

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

Источник

How to run a script after user login authentication in linux

I have a script which I want to run just after user log-in authentication. To accomplish this, I added the script name in /etc/rc5.d/S##rc.local file. But later i got to know that, anything that is added in rc.local file gets executed in boot time of the system not after the login authentication. Can anyone tell me how to run the script after user login authentication?

Are you doing this for convenience or for security? I.e. do you just want to set up your login environment (add aliases, set variables, etc), or do you want your script to run after each login without allowing users to remove it?

3 Answers 3

You can add your script to /etc/profile.d folder.

More reading about this here and here.

Basically, you should give your script the extension .sh as all these files are executed in a loop after user logs on.

@user976754: I am glad it helped you. Please mark my answer as your accepted answer for this question 🙂

It looks like you need to have root permissions to create files under /etc/profile.d How then does the file get executed when the user logs in? As the file will be owned by root.

@ams Requiring root permissions for creating script file does not imply it has to be run as root. Files in /etc are always considered affecting a whole system which is implying affection on all users of that system. You definitely don’t want to have anyone writing scripts to be run as you log on with «anyone» including user accounts used to run network services like webserver, only.

Источник

How do I start applications automatically on login?

15 Answers 15

20.04 and later

  1. If not yet done by default install gnome-startup-applications
  2. Search and open «Startup Applications» screenshot
  3. click add to enter the command including options of your application as you would run it from terminal (you may have to give in the full path if it runs from a non-standard location) screenshot
  • This will add a .desktop file in your ~/.config/autostart screenshot
Читайте также:  Linux команды диспетчер устройств

14.04 and later

screenshot

  1. Open the Dash and search for «Startup Applications»
  2. Now click on Add and give in the command to run the application. This can be found in Main Menu if installed (see below)

Using Main Menu (alacarte) to find the terminal command to run a given program:

  1. Firstly open the program ‘Main Menu’ (type Menu in the Dash) screenshot
  2. Now select the program which you want to add to startup and click on properties . screenshot
  3. Now note the command for that program . screenshot

Non GUI approach

Advanced users may want to manually put a .desktop file in ~/.config/autostart to run applications after a user login. This may have following content:

[Desktop Entry] Type=Application Name= Exec= Icon= Comment= X-GNOME-Autostart-enabled=true 

You may have to give this file execute permission.

Источник

How to write a shell script that gets executed on login?

I am trying to write bash shell script in Ubuntu 11.10 Linux distro, that will get executed automatically on logging into the system. But I am not able to figure out that what to write in script that by it will get automatically executed on logging in.

The solution would vary depending on what «log in» actually means. If it means «starting a login shell (in a terminal, for example)», then most of the answers below would help, but if you mean that the script should run as soon as you log into a graphical desktop environment, without ever starting a terminal or shell session, then you may want to clarify this in the question.

5 Answers 5

If you want it to be global, modify

If you want it to be user-specific, modify

Don’t forget that the extension should be .sh if you put your script inside of /etc/profile.d/ . chmode +x /etc/profile.d/myscript.sh of course too.

Raspbian Stretch. Trying to run /usr/local/bin/pihole -c command on autologin of specific user. Added this line to /home/$USER/.profile — nothing happens. When I add script to /etc/profile.d then it works, but it’s global and runs it even when I open ssh session(which is not what I want). Adding to .bashrc works too, but runs any time I open new shell (which is no what I want). Question: Why adding to /home/$USER/.profile wouldn’t work.

This would run the script every time the user starts a login shell, regardless of whether they have just logged in or not. It is unclear whether it would run when the user logs in (e.g. via a graphical display manager; it would depend on the setup of their system).

/etc/profile or $HOME/.profile or $HOME/.bash_profile

I would highly recommend against using /etc/profile.d/yourscript.sh if it produces output. When you use a non-interactive session, you will receive a $TERM is not set message. This is noticeable when using the ssh protocol, like scp. Usually not a big deal, however, Veeam doesn’t like it and will throw a warning. I know Veeam is not the topic here, but it’s worth mentioning that not all applications will gracefully ignore the $TERM is not set warning.

Читайте также:  Kaspersky endpoint security линукс

In short, if the script generates output, place it in the locations specified on the first line. However, if you’re modifying the environment and your script doesn’t generate output, then use the latter.

Whether or not this would be executed when the user logs in depends on whether the user starts a login shell or not (which they might not do if they log in via a graphical display manager). It is unclear from the question what the user means by «logging in». In any case, your suggestion would mean the script is run each time the user starts a login script, not just when logging in.

If you want to be more bash specific you can also write you code in ~/.bash_profile or ~/.bash_login.

And you can source any script therein for example:

if [ -f ~/.bashrc ]; then source ~/.bashrc fi 

Just a data point since the question is tagged Ubuntu.

Under Ubuntu 20.04 and 22.04, the only option to autoload of a script/command at each login is (that worked for me) to add it in

As stated in the comments, adding it to ~/.profile doesn’t seem to invoke the script. Adding it to /etc/profile.d/ is not per login.

To execute a shell script on login in Ubuntu 11.10, you can add your script to the ~/.bashrc file. This file is executed each time a login shell starts up, so any commands or scripts added here will be run whenever you log in to your system. To add your script to ~/.bashrc, Open a terminal and navigate to your home directory by typing: cd ~/ Next, open the .bashrc file in a text editor using the following command: nano .bashrc Once you have the file open, navigate to the end of the file and add the following line: /path/to/your/script.sh Make sure to replace «/path/to/your/script.sh» with the actual path to your script. Also, make sure that your script is executable by running: chmod +x /path/to/your/script.sh Save and close the file, and the next time you log in, your script should be executed automatically. Let me know if it works for you!

The ~/.bashrc file is sourced each time an interactive shell is started, no matter if the user has just logged in or not.

Источник

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