I would like to know how I can execute a local server script, for instance send a mail using mailx, when a ssh session is opened, pre-login stage.

When a ssh connection comes into the server, I would like to action a script pre-login.


Client_SSH >> **{server_script_exec}** >> login_prompt  >> Server       [login failed]

I have tried searching for this, but I only seem to get scripts that execute after login, like through .bashrc

I know I'm opening myself up to some flooding, however I would like to learn about the pre-login process. The server is in a controlled environment, and not exposed to the www.

  • see the sshd_config man page and the ForceCommand. Get it to run your script which should end with $SSH_ORIGINAL_COMMAND. – meuh Aug 25 '15 at 8:40

You can use PAM for this. The PAM configuration for the SSH service is in /etc/pam.d/sshd. To run a command before anything in the login process, add something like:

auth [default=ignore] pam_exec.so /path/to/some/script

For example, if I use /usr/local/bin/foo.sh containing:

#! /bin/sh

cat <<EOF >>/tmp/log

And then I do ssh muru@localhost, I get:

$ cat /tmp/log
PAM_RHOST localhost

This doesn't happen before the password prompt shows up, but auth modules are the first ones run after the password is entered - they check whether the user is authenticated, after all:

   authentication - authenticate a user and set up user credentials.
   Typically this is via some challenge-response request that the user
   must satisfy: if you are who you claim to be please enter your
   password. Not all authentications are of this type, there exist
   hardware based authentication schemes (such as the use of smart-cards
   and biometric devices), with suitable modules, these may be substituted
   seamlessly for more standard approaches to authentication - such is the
   flexibility of Linux-PAM.

So, in effect, auth modules run before login, and if the first auth module is pam_exec, that's pretty much the first thing to run.

Note the [default=ignore] part - since auth modules authenticate the user, we don't want the script's exit status to mean anything. default=ignore tells PAM to ignore pam_exec's return value, whatever it may be, which in turn depends on the script's exit status. See man pam.d for more details.


  • This doesn't run if the user just quit before entering any password.
  • This doesn't run if the user provided an empty password (the default SSH configuration has PermitEmptyPasswords no, so SSH rejects those out of hand).
  • SSH needs to have UsePAM yes for it to use PAM.
  • Just wanted to add that on Ubuntu 18.04.03, the session /etc/pam.d/sshd entry worked, not auth: session [default=ignore] pam_exec.so /path/to/my/script.sh – AnythingIsFine Dec 20 '19 at 12:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.