Run (system) script on SSH login and/or logout

You can force a command onto your SSH-users instead of the one they request (or their shell if they don't give a specific command). This can be done by specifying that command with something like ForceCommand /root/ssh-wrapper in /etc/ssh/sshd_config (it doesn't matter where the script is located or how it's named, just make sure it is executable by all users and the sshd configuration file points to it). You also need to restart/reload sshd. The original command is accessible to the forced command as $SSH_ORIGINAL_COMMAND.

I just hacked this script together:

#! /bin/sh

# add logger options when needed
log="logger -t ssh-wrapper"

# find IP address
ip=`echo $SSH_CONNECTION | cut -d " " -f 1`

$log $USER login from $ip
espeak "$USER just logged in from $ip" > /dev/null 2>&1

$log command: ${SSH_ORIGINAL_COMMAND:-shell}
${SSH_ORIGINAL_COMMAND:-shell}

$log $USER logout
espeak "$USER just logged out" > /dev/null 2>&1

Now every time I login or logout a voice tells me about it, and a log entry gets written to syslog. It also logs the command. You can use something like the following to "follow" your sshd usage:

tailf /var/log/syslog | grep ssh-wrapper

Please note that this script is mostly untested, so use at your own risk! ;-)

PS: remember that this script is run as the user that logged in, so you can't do everything you want if you change it to add more features...