How to automatically run commands on SSH login?
Solution 1:
Put the commands in ~/.bashrc
. Anything in there is executed each time you log in.
If you need commands to only run when logging in via ssh (but not when logging in physically), you could probably test for the presence of the SSH_CONNECTION
environment variable, and only run the commands if you find it exists.
Solution 2:
Just put this in ~/.bashrc
or /etc/bash.bashrc
if you want this for all users:
if [[ -n $SSH_CONNECTION ]] ; then
echo "I am logged in remotely"
fi
Solution 3:
Alternatively, you can specify a command to be run during the invocation of ssh
:
$ ssh -t server 'cmd; exec bash -l'
The last command in the list should start an interactive session in your preferred shell. If you have a lot of commands to run, consider creating a script file on your SSH server.
Solution 4:
Actually ~/.ssh/rc
is a right place for you to add command to run when you log in, rather than any user of the system.
~/.ssh/rc
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.