If you want to run a script after any user logs into your server, you can achieve this by using the ForceCommand
directive in the sshd_config file. The ForceCommand
will run before any user-supplied commands and before they are given access to a shell.
Follow these steps to set it up:
Edit the
/etc/ssh/sshd_config
file using your preferred text editor. You may need superuser privileges to do this:$ sudo nano /etc/ssh/sshd_config
Add the following lines to the
sshd_config
file:Match User * ForceCommand /bin/bash -c "/path/to/script && exec $SHELL"script"
Some important notes:
- The
exec $SHELL
is included to ensure thatThis will override the process of ssh running the user still gets their shell session after, so that will have to be added to the script executionas done below. - You can change
&&
to&
if your script is time-consuming. Using&&
will block themake this user from interacting untilspecific by putting the script is complete. However if you are having trouble withscp
after this change, reviewing this choice might helpusername in place of the star.
- The
Here's an example of what your script could look like:
#!/bin/bash
# Create a welcome file for the user
touch ~$USER/welcome
# Check if the user is sending a specific command via SSH
if [[ $SSH_ORIGINAL_COMMAND ]]; then
execeval /bin/bash"$SSH_ORIGINAL_COMMAND"
else
-c "$SSH_ORIGINAL_COMMAND" # !!NB!!
# if the user has not specified a ssh command run their shell
exec $SHELL
fi
The script first creates a welcome file in the user's home directory. Then, it checks if the user is sending a specific command via SSH and, if so, executes that command after the script has completed.
Don't forget to restart your sshd service
with either $ sudo systemctl restart sshd.service
or $ sudo service ssh restart
depending on your system.