Ubuntu/Debian/OpenSSH: Run (system) script on SSH login and/or logout

scriptingsshUbuntu

On Ubuntu, I'd like my OpenSSH server to start a script whenever a user logs in using SSH, ideally passing the host name or IP, as well as the user name. Additionally I'd like it to run a script, whenever a session is terminated (passing the username). These scripts should not run in the user's session, but system wide.

The idea is to give an audio warning on login and logout, e.g. using espeak, and to display the information on an external display.

I've seen that there is a pam-scripts package but I'm not sure if this does what I want, nor how to use it.

Any help is appreciated!
— Markus

(I also posted this question on askubuntu.)

Best Answer

Here's a wrapper script to be called by ForceCommand in sshd_config. This differentiates between a login command and a command invoked via ssh like ssh host "ls -l", since you might want to handle those differently.

#!/bin/bash

if [ -n "$SSH_ORIGINAL_COMMAND" ]; then
    eval $SSH_ORIGINAL_COMMAND
else
    echo "LOGIN: $USER $SSH_CONNECTION" >> /tmp/ssh.log
    $SHELL
    echo "LOGOUT: $USER $SSH_CONNECTION" >> /tmp/ssh.log
fi

You can replace the echo commands with whatever you'd like. IP information is in $SSH_CONNECTION, do with it what you will.

If you call this /usr/local/bin/ssh-command.sh, you would add this to your sshd_config:

ForceCommand /usr/local/bin/ssh-command.sh

It is probably a good idea to use Match as well to only trap certain users. Assuming all the users are in the "gobias" group:

Match Group gobias
    ForceCommand /usr/local/bin/ssh-command.sh

Anyway, perhaps it's worth a shot.