我经常必须登录到几个服务器中的一个,然后进入这些机器上的几个目录中的一个。目前我做的事情是这样的:

localhost ~]$ ssh somehost

Welcome to somehost!

somehost ~]$ cd /some/directory/somewhere/named/Foo
somehost Foo]$ 

我有脚本,可以确定哪个主机和哪个目录,我需要进入,但我不知道如何做到这一点:

localhost ~]$ go_to_dir Foo

Welcome to somehost!

somehost Foo]$

有没有简单、聪明或任何方法可以做到这一点?


当前回答

连接用户

In case if you don't know this, you can use this to connect by specifying both user and host
ssh -t <user>@<Host domain / IP> "cd /path/to/directory; bash --login"

例如:ssh -t admin@test.com "cd public_html;bash——登录”

您还可以在每次登录时通过在双引号中使用a;每次命令前

其他回答

用-t思想更进一步。我保留了一组脚本,调用下面的脚本访问我经常访问的主机中的特定位置。我将它们都保存在~/bin中,并将该目录保存在我的路径中。

#!/bin/bash

# does ssh session switching to particular directory
# $1, hostname from config file 
# $2, directory to move to after login
# can save this as say 'con' then
# make another script calling this one, e.g.
# con myhost repos/i2c

ssh -t $1 "cd $2; exec \$SHELL --login"

你可以加上

cd /some/directory/somewhere/named/Foo

到另一个主机上的.bashrc文件(或.profile或其他任何名称)。这样,无论您做什么或从哪里使用ssh,无论您何时登录到该服务器,它都将cd到适合您的目录,您所要做的就是像平常一样使用ssh。

骂人的是,rogeriopvl的解决方案也工作,但它有点啰嗦,而且你必须记住每次都这样做(除非你做一个别名),所以它似乎有点不“有趣”。

我已经创建了一个工具,SSH和CD到一个服务器连续-恰当地命名为sshcd。对于你给出的例子,你可以简单地使用:

sshcd somehost:/some/directory/somewhere/named/Foo

如果你有任何问题或问题,请告诉我!

根据@rogeriopvl的回答,我建议如下:

ssh -t xxx.xxx.xxx.xxx "cd /directory_wanted && bash"

使用&&链接命令将使下一个命令只在前一个命令成功时运行(与使用;相反,它按顺序执行命令)。当需要cd到执行该命令的目录时,这特别有用。

想象一下这样做:

/home/me$ cd /usr/share/teminal; rm -R *

目录teminal不存在,这导致您停留在主目录中,并使用以下命令删除其中的所有文件。

如果你使用&&:

/home/me$ cd /usr/share/teminal && rm -R *

如果找不到目录,该命令将失败。

我使用环境变量CDPATH