Change default directory when I SSH to server

Solution 1:

There are two ways to achieve this:

  • Change your homedirectory on the server to /var/www/websites (this is not really a good idea)
  • add cd /var/www/websites to the end of your .bashrc. I use this one on our puppetmasters as I always want to be in /etc/puppet/environments/dkaarsemaker there instead of my homedir :-)

Solution 2:

If you use keys for SSH login then you can change path by prepending command= to before a key in ~/.ssh/authorized_keys on your remote server. Example:

command="cd /var/www/websites ; /bin/bash -l" ssh-rsa AAA.....rest of the key

It is fine to generate and use multiple keys for the same user. One key on the server may contain the command the other may not - this way you select expected behaviour at login time. You can simply wrap it up with local ~/.ssh/config:

Host websites-my-host
    HostName <realhostname>
    IdentityFile ~/.ssh/<key1>  #on the server key with "command"
    User webmaster

Host my-host
    HostName <realhostname>
    IdentityFile ~/.ssh/<key2>  #on the server key without command
    User webmaster

This is what will occur:

local$ ssh websites-my-host
webmaster@realhostname:/var/www/websites$ _

or:

local$ ssh my-host
webmaster@realhostname:~$ _

Solution 3:

Openssh sshd by default accepts these environment variables from the client:

AcceptEnv LANG LC_*

You can use that to send a value from the local environment of the client to the server like this:

LC_CDPATH=/var/www/websites ssh -o SendEnv=LC_CDPATH user@server

You can place the SendEnv directive in ~/.ssh/config so you don't have to include it on the command line.

If you place the following in your ~/.profile (to only affect interactive logins use .profile, to affect all logins use .bashrc):

if [ "$LC_CDPATH" -a -d "$LC_CDPATH" ]; then
  cd "$LC_CDPATH";
fi

Then it will automatically change directory to the one specified in the environment variable when you login, if it is specified and if it is a directory.


Solution 4:

Since OpenSSH 7.6, you can use the new RemoteCommand option to achieve that.

In your ~/.ssh/config:

Host websites-my-host
    HostName <realhostname>
    IdentityFile ~/.ssh/keyfile
    User webmaster
    RequestTTY force # check if this is necessary
    RemoteCommand cd /var/www/websites && bash -l

Tags:

Linux

Ubuntu

Ssh