Perform action when user logs in via SSH from a particular host

Tamas picture Tamas · Oct 8, 2012 · Viewed 11.9k times · Source

I have a quesiton that puzzles me and I wonder if anyone has attempted to achieve the following:

Let's assume that this is the result of my 'last' command in a Linux environment:

root  pts/1        192.168.1.10      Wed Feb 10 07:04 - 07:57  (00:52)  
root  pts/2                          Tue Feb  9 22:00 - 00:13  (02:13)   

How can I setup a particular action (say for example a modified MOTD or sending an email) if the the 'root' user has logged in from 192.168.1.10. Is there a way of capturing this information?

The second part of this question is that how can I make the above check a bit more robust - i.e. if I have the following:

mary  pts/1        192.168.1.10      Wed Feb 10 07:04 - 07:57  (00:52)  
bob   pts/2                          Tue Feb  9 22:00 - 00:13  (02:13)      

Now I'd like to perform an action if the username is equal to 'mary' and the host is 192.168.1.10.

Any suggestions are welcomed.

Thank you in advance.

Answer

Gilles Quenot picture Gilles Quenot · Oct 8, 2012

There's a special file /etc/ssh/sshrc where you can put some commands that will runs each time someone connect by ssh. I wrote that for you :

#!/bin/bash

[email protected]
monitored_user=root
monitored_ip=x.x.x.x

hostname=$(hostname)

# add a welcome message:
printf >&2 "\nWelcome on $hostname $USER\n"

read -d " " ip <<< $SSH_CONNECTION

[[ $ip == $monitored_ip && $USER == $monitored_user ]] || exit 0

date=$(date "+%d.%m.%Y %Hh%M")
reverse=$(dig -x $ip +short)

mail -s "Connexion of $USER on $hostname" $mail <<EOF

IP: $ip
Reverse: $reverse
Date: $date
EOF

Put this script in a file, then put the full path of the script in /etc/ssh/sshrc

In man ssh :

/etc/ssh/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.