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

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

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


当前回答

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

其他回答

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

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

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

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

我的答案可能与你真正想要的不同,但我在这里写的可能对一些人有用。在我的解决方案中,您必须进入该目录一次,然后每个新的ssh会话都将进入相同的目录(在第一次登出之后)。

如何ssh到相同的目录,你已经在你上次登录。 (我假设您在远程节点上使用bash。)

将这一行添加到~/。远程节点上的Bash_logout (!):

echo $PWD > ~/.bash_lastpwd

这些到~/的直线。Bashrc文件(仍然在远程节点上!)

if [ -f ~/.bash_lastpwd ]; then
    cd $(cat ~/.bash_lastpwd)
fi

这样在每次登出时保存当前路径,登录后.bashrc将您放入该目录。

ps:你可以进一步调整它,比如使用SSH_CLIENT变量来决定是否进入该目录,这样你就可以区分本地登录和ssh,甚至不同的ssh客户端。

连接用户

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

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

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

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

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

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

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