How can I ssh directly to a particular directory?

前端 未结 12 2095
情话喂你
情话喂你 2020-12-07 07:03

I often have to login to one of several servers and go to one of several directories on those machines. Currently I do something of this sort:

localhost ~]$ ssh          


        
12条回答
  •  -上瘾入骨i
    2020-12-07 07:46

    My preferred approach is using the SSH config file (described below), but there are a few possible solutions depending on your usages.

    Command Line Arguments

    I think the best answer for this approach is christianbundy's reply to the accepted answer:

    ssh -t example.com "cd /foo/bar; exec \$SHELL -l"
    

    Using double quotes will allow you to use variables from your local machine, unless they are escaped (as $SHELL is here). Alternatively, you can use single quotes, and all of the variables you use will be the ones from the target machine:

    ssh -t example.com 'cd /foo/bar; exec $SHELL -l'
    

    Bash Function

    You can simplify the command by wrapping it in a bash function. Let's say you just want to type this:

    sshcd example.com /foo/bar
    

    You can make this work by adding this to your ~/.bashrc:

    sshcd () { ssh -t "$1" "cd \"$2\"; exec \$SHELL -l"; }
    

    If you are using a variable that exists on the remote machine for the directory, be sure to escape it or put it in single quotes. For example, this will cd to the directory that is stored in the JBOSS_HOME variable on the remote machine:

    sshcd example.com \$JBOSS_HOME
    

    SSH Config File

    If you'd like to see this behavior all the time for specific (or any) hosts with the normal ssh command without having to use extra command line arguments, you can set the RequestTTY and RemoteCommand options in your ssh config file.

    For example, I'd like to type only this command:

    ssh qaapps18
    

    but want it to always behave like this command:

    ssh -t qaapps18 'cd $JBOSS_HOME; exec $SHELL'
    

    So I added this to my ~/.ssh/config file:

    Host *apps*
        RequestTTY yes
        RemoteCommand cd $JBOSS_HOME; exec $SHELL
    

    Now this rule applies to any host with "apps" in its hostname.

    For more information, see http://man7.org/linux/man-pages/man5/ssh_config.5.html

提交回复
热议问题