Run scripts automatically in server after ssh connection

how to run a script automatically in server soon after client system establish ssh connection with the server

for ex: suppose a user will logon to my computer from another system(connected via lan) using ssh connection. At that time, A script(python or shell) should be run automatically in my system to perform some validation?

How to run the script automatically in server system?


Solution 1:

You can do so by adding the following parameter to your config file (/etc/ssh/sshd_config).

 ForceCommand
         Forces the execution of the command specified by ForceCommand, ignoring any command supplied by the client and ~/.ssh/rc if present.  The command is invoked by using the user's login shell
         with the -c option.  This applies to shell, command, or subsystem execution.  It is most useful inside a Match block.  The command originally supplied by the client is available in the
         SSH_ORIGINAL_COMMAND environment variable.  Specifying a command of “internal-sftp” will force the use of an in-process sftp server that requires no support files when used with
         ChrootDirectory.

An other option is to use the .ssh/rc files on a per user basis.

To use the ForceCommand method you just add ForceCommand /usr/bin/ownscript at the bottom of the file /etc/ssh/sshd_config (on the server).

The script looks like this:

#!/bin/bash
#Script file for ssh
#
#put your commands here
echo "test" > /tmp/test.txt
#
#exit by calling a shell to open for the ssh session
/bin/bash

Don't forget to chmod the script sudo chmod +x /usr/bin/ownscript

Solution 2:

You can create a /etc/ssh/sshrc file. See man 8 ssh. If you want this for a single user, use ~/.ssh/rc.

Here is a sample /etc/ssh/sshrc that will notify you via dbus when someone logs in on your machine. Don't forget to chmod +x:

#!/bin/bash

ip=`echo $SSH_CONNECTION | cut -d " " -f 1`

notify-send -u CRITICAL "SSH connection from ${ip}" "User $USER just logged in from $ip"

Solution 3:

For execution of a script during logon, add it as a call from within the /etc/profile script. This is executed for every logon, not only for ssh logons.