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

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]$

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


当前回答

你可以加上

cd /some/directory/somewhere/named/Foo

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

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

其他回答

连接用户

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;每次命令前

你可以加上

cd /some/directory/somewhere/named/Foo

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

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

不幸的是,建议的解决方案(@rogeriopvl)在使用多个跳时不起作用,所以我找到了另一个。 在远程机器上添加到~/。Bashrc:

[ "x$CDTO" != "x" ] && cd $CDTO

这允许你在命令行上以这样的方式指定所需的目标目录:

ssh -t host1 ssh -t host2 "CDTO=/desired_directory exec bash --login"

当然,这种方式也可以用于单跳。

这个解决方案可以与@redseven的有用提示相结合,以获得更大的灵活性(如果没有$CDTO,则转到保存目录,如果存在的话)。

SSH本身提供了一种通信手段,它不知道任何关于目录的信息。因为您可以指定要执行哪个远程命令(默认情况下,这是您的shell),所以我将从这里开始。

用-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"