How can I configure my server to notify me whenever it is remotely accessed via ssh?

Solution 1:

pam_script will run any program you want when a user logs in.

Solution 2:

You should be able to do so with a rule in /etc/hosts.allow. Try something like:

sshd: ALL: (/usr/bin/echo "SSH connection from %h (%H)" | /usr/bin/mailx -s "SSH Alert" [email protected]) 

You can get more detail from a script run from /etc/profile.d, or included in /etc/profile. However, this will only work if the user logs in to an interactive session.

If you don't need immediate notification, the logcheck program can notify you hourly of any accesses in the last hour. You will need to add appropriate rules to the configuration.

EDIT: Ubuntu uses the incompatible hosts_options format to execute shell commands. The follow rule is what I implemented:

SSHD: ALL: spawn (/bin/echo "SSH connection to %H from %h[%a]" | \
     /usr/bin/mailx -s "SSH Alert" [email protected])

Notes: Backslash notation can be used to wrap lines as above. Substitution characters are documented in the hosts.allow man page.