19

Is there a way to run a script/command every time a user connects using ssh? Can it be configured globally (i.e run the script when any user login)?

I came across this question on Identica, but there is no answer yet and would like to know it anyway.

2 Answers 2

16

For all users, or a particular user? For a single user, set it in their .bashrc file; for all users, check out pam_exec.

If the users are coming in from sshd, you'll want to add the following line to /etc/pam.d/sshd; other files depending on their source:

session optional pam_exec.so seteuid  /path/to/my/hook.sh

For testing purposes, the module is included as optional, so that you can still log in if it fails. After you made sure that it works, you can change optional to required. Then login won't be possible unless the execution of your hook script is successful.

Note: As always when you change the login configuration, leave a backup shell open in the background and test the login from a new terminal.

6
  • Thanks, that looks promising. Can you elaborate a bit more? I'm unfamiliar with this.
    – phunehehe
    Feb 14, 2011 at 16:05
  • I suppose that I should add session include pam_exec.so seteuid /path/to/script to the file /etc/pam.d/system-remote-login. Is that correct?
    – phunehehe
    Feb 14, 2011 at 16:07
  • Either system-remote-login or sshd, depending on how the user is coming in. Feb 14, 2011 at 16:07
  • Awesome! It would be great if you edit the answer to include the information (you know, for others who search for it).
    – phunehehe
    Feb 14, 2011 at 16:13
  • 1
    Note to people googling, you can also put this line auth optional pam_exec.so /path/to/my/hook.sh in /etc/pam.d/common-auth to have PAM notify you of ANY authentication events that occur. This program can also send you push notifications: github.com/benjojo/PushAlotAuth Jan 29, 2016 at 21:10
8

there's another way which only influences users using ssh not local ones (which might be better in emergency situations)

see the snippets from the ssh man page below.

in this case the users can usually modify the files themselves (a bit like .bashrc)

 ~/.ssh/rc
         Commands in this file are executed by ssh when the user logs in, just before the user's shell (or command) is started.  See the sshd(8) manual page for more information.

and this is global and not modifiable by the normal user

 /etc/sshrc
         Commands in this file are executed by ssh when the user logs in, just before the user's shell (or command) is started.  See the sshd(8) manual page for more information.
2
  • 2
    But /etc/sshrc will be executed only if user do not have own ~/.ssh/rc, so this user can bypass
    – isevcik
    Feb 7, 2013 at 21:02
  • 2
    @isevcik, that is only if PermitUserRC is set to "yes" in /etc/ssh/sshd_config (see man sshd_config for details) Jul 11, 2018 at 16:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .