我怎样才能自动改变目录在SSHlogin?

我试图让sshssh时自动切换到一个特定的目录。我尝试使用~/.ssh/config的以下指令来获取这个行为:

 Host example.net LocalCommand "cd web" 

但每当我login,我看到以下内容:

 /bin/bash: cd web: No such file or directory 

尽pipe在我的主目录中肯定有一个web文件夹。 即使使用绝对path也会提供相同的消息。 要清楚的是,如果我login后inputcd web ,我到达正确的文件夹。

我在这里错过了什么?

编辑:

引号/绝对path的不同组合给出了不同的错误信息:

 LocalCommand "cd web" /bin/bash: cd web: No such file or directory LocalCommand cd web /bin/bash: line 0: cd: web: No such file or directory LocalCommand cd /home/gareth/web /bin/bash: line 0: cd: /home/gareth/web: Input/output error 

这让我觉得报价不应该在那里,而且还有另一个错误发生。

    cd是一个内置的shell。 LocalCommand被执行为:

     /bin/sh -c <localcommand> 

    你想要做的事情不能通过SSH来完成; 您需要以某种方式修改shell,例如通过bashrc / bash_profile。

    这工作:

     ssh server -t "cd /my/remote/directory; bash --login" 

    要创build一个目录,如果它不存在:

     ssh server -t "mkdir -p newfolder; cd ~/newfolder; pwd; bash --login" 

    如果你不把bash添加到path的末尾,那么你在cd命令运行后退出。 如果你不添加--login那么你的~/.profile不是来源的。

    1. login到你的盒子
    2. 编辑~/.bash_profile
    3. 在文件的末尾添加cd /path/to/your/destination
    4. 保存并退出编辑器
    5. 从框中注销
    6. 再次login,您应该将其login到/path/to/your/destination

    当您需要ssh并覆盖默认的.bashrc文件的情况下更强大的解决scheme。 这在远程服务器环境具有多个docroot并被多个用户使用的情况下是有用的。

     alias ssh_myserver='ssh server_name -t "echo cd /path/to/desired/dir>/tmp/.bashrc_tmp; bash --rcfile /tmp/.bashrc_tmp"' 

    更详细的:

    1. 第一个命令在远程服务器上的/tmp目录中创build.bashrc_tmp文件,内容为cd /path/to/dir
    2. Next命令执行步骤1中指定的configuration文件bash 。这允许切换到所需的dir并禁止默认的.bashrc
    3. 整个命令被封装成一个alias ,所以在ssh客户端命令提示符下它可以被称为ssh_myserver

    你有没有尝试过,没有报价呢? 我见过的唯一的例子没有他们,所以他们可能试图执行cd \ web作为命令。

    在你的~/.ssh/config

     LocalCommand echo '/home/%r/some/subdir' > /home/%r/.ssh/ssh_cd 

    ~/.bashrc结尾:

     if [[ -f $HOME/.ssh/ssh_cd ]] then cd $(<$HOME/.ssh/ssh_cd) # uncomment the line below and the file will be removed so the cd won't work # unless the file is regenerated since you may not want this to operate for # non-ssh logins or for ssh logins that you want to function differently # rm $HOME/.ssh/ssh_cd fi 

    我试图使用variables传递,包括一个导出的variables,但这些命令运行在不同的shell。

    顺便说一句,当testing你正在尝试做什么时,我没有遇到错误,当我使用无引号的绝对path。 我补充说 ; pwd在命令结尾并显示正确的目录,但是最终的目录是~ 。 在我的shell启动文件中没有cd命令。 我试图把一个不同的cd somedir; pwd cd somedir; pwd~/.ssh/rc (另一个依然存在)。 config命令在发出motd之前执行,而rc命令之后发出,但在shell启动文件来源之前。 所以再次,这是发生在一个不同的壳。

    尝试通过文件传输技术,让我知道,如果它适合你。

    所以我search了很多网站(stackoverflow,这一个),但没有find我想要的。 我结束了创build我自己的shell脚本。 我在这里粘贴。 你也可以在$ PATH中拷贝一个目录。

     #!/bin/bash ssh -t <username@hostname> "cd ~/$1; exec \$SHELL --login" 

    所以在这之后 我做:

     connect <foldername> 

    注意:更改pathvariables后,您可能需要注销并重新login

    你在你的SSHconfiguration中启用了这个指令吗?

     PermitLocalCommand yes 

    默认值是no ,在这种情况下你的LocalCommand指令将被忽略。

    或者,您是否尝试将命令添加到.bashrc文件?

    你也可以试试这个,用-t选项:

    ssh服务器-t“cd / my / remote /目录; bash”