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

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

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


当前回答

我知道这个问题很久以前就有答案了,但我在尝试将ssh登录合并到bash脚本中时发现了这个问题,登录后运行几个命令,然后注销并继续使用bash脚本。我发现的最简单的方法,在其他地方没有提到,因为它是如此琐碎,就是这样做。

#!/bin/bash

sshpass -p "password" ssh user@server 'cd /path/to/dir;somecommand;someothercommand;exit;'

其他回答

登录后直接进入的另一种方法是创建“别名”。当你登录系统时,只要输入这个别名,你就会在那个目录下。

示例:Alias = myfolder '/var/www/Folder'

登录到系统后,输入该别名(这可以从系统的任何部分进行) 这个命令如果不在bashrc中,将适用于当前会话。因此,您还可以将这个别名添加到bashrc,以便将来使用它

$ myfolder =>带您到该文件夹

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

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

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

我知道这个问题很久以前就有答案了,但我在尝试将ssh登录合并到bash脚本中时发现了这个问题,登录后运行几个命令,然后注销并继续使用bash脚本。我发现的最简单的方法,在其他地方没有提到,因为它是如此琐碎,就是这样做。

#!/bin/bash

sshpass -p "password" ssh user@server 'cd /path/to/dir;somecommand;someothercommand;exit;'

简单地修改你的家命令: Usermod -d /newhome用户名

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