Whenever I login to my Linux server I'd like to have several commands run automatically (set some variables, change location, etc.)
This needs to be done on user login, not on system start.
How can I set it to do this?
16 Answers
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.
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 6 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.
1Actually ~/.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. 3 If you use a config file on your system, you can embed a startup command that will only execute when you connect the machine.
For this, first run
nano ~/.ssh/configto open the config file. Then you can insert / edit it to contain something like this:
Host myhost HostName *.*.*.* User root RequestTTY force RemoteCommand cd / && bash -iThis sample will cd in the root of the server. && bash -i and RequestTTY force are essential to continue usage of the remote terminal.
Don't forget to input the right IP in HostName, then install your public key on the target machine that you can retrieve like so:
~/.ssh/id_rsa.pubAnd install on the remote like so:
mkdir -p ~/.ssh && chmod 700 ~/.ssh && touch ~/.ssh/authorized_keys && chmod 644 ~/.ssh/authorized_keys && echo "YOUR_PUBLIC_KEY" >> ~/.ssh/authorized_keysThen you can simply connect the machine like so:
ssh myhostAnd it will connect and execute the RemoteCommand.
To have a script that will execute for any user on login you can add an additional script in:
/etc/profile.d/For example:
/etc/profile.d/Hello.sh
Hello `whoami`On login would produce:
$ ssh MyTestUser@localhost
Hello MyTestUserThe profile script is executed as the user that is logging in. This may or may not be a problem depending on what you want the script to do.