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

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


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/bashmail=user@domain.tldmonitored_user=rootmonitored_ip=x.x.x.xhostname=$(hostname)# add a welcome message:printf >&2 "\nWelcome on $hostname $USER\n"read -d " " ip <<< $SSH_CONNECTION[[ $ip == $monitored_ip && $USER == $monitored_user ]] || exit 0date=$(date "+%d.%m.%Y %Hh%M")reverse=$(dig -x $ip +short)mail -s "Connexion of $USER on $hostname" $mail <<EOFIP: $ipReverse: $reverseDate: $dateEOF

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.


Thanks for all your replies. Eventually I managed to find a solution which does work for the time being but it does have one flaw which I'll point out in a minute.

I have added the following to my /etc/bashrc file (or /etc/bash.bashrc whatever environment you're using):

HOST="192.168.0.1"RHOST=`who am i | sed -n 's/.*(\([^) ]*\).*/\1/p; 1q'`if [ "$RHOST" == "$HOST" ]; then        echo "SAY WHAT!"        #add further actions here if neededfi

The flaw that I was talking about before may actually not be a flaw. If you're already SSH-ed into the system, and you want to SSH to a host which lives on the same IP, say ssh root@your-host who am i would then print 'your-host' but I think that's the way it should be.

Needless to say that the above sed statement can be modified so you can capture the username as well, and you can extend the if/else statement to suite your needs.

Thank you again for all your replies.


You can add something to /etc/profile or equivalent that does something depending on the value of $SSH_CLIENT.