我试图让ssh
在ssh
时自动切换到一个特定的目录。我尝试使用~/.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
不是来源的。
~/.bash_profile
cd /path/to/your/destination
/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"'
更详细的:
/tmp
目录中创build.bashrc_tmp
文件,内容为cd /path/to/dir
bash
。这允许切换到所需的dir并禁止默认的.bashrc
。 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”