如何从一个bash脚本中ssh?

我试图创build一个SSH连接,并在脚本内的远程服务器上做一些事情。

然而,terminal提示我input密码,然后在terminal窗口而不是脚本中打开连接。 在我退出连接之前,命令不会被执行。

我怎么能从一个bash脚本ssh?

  1. 如果您想让密码提示消失,请使用基于密钥的身份validation( 此处介绍 )。

  2. 要通过ssh远程运行命令,您必须将它们作为ssh的参数,如下所示:

root @ host:〜#ssh root @ www'ps -ef | grep apache | grep -v grep | wc -l'

如果你想继续使用密码,而不是使用密钥交换,那么你可以用'期望'来实现这个:

 #!/usr/bin/expect -f spawn ssh user@hostname expect "password:" sleep 1 send "<your password>\r" command1 command2 commandN 

还有另外一种使用Shared Connections的方法,即:有人使用密码启动连接,每个后续连接都将在同一个通道上进行多路复用,从而不需要重新authentication。 (而且它也更快)

 # ~/.ssh/config ControlMaster auto ControlPath ~/.ssh/pool/%r@%h 

那么你只需要login,只要你login,bash脚本将能够打开ssh连接。

当有人尚未打开频道时,您可以停止工作:

 ssh ... -o KbdInteractiveAuthentication=no .... 

你需要做的是为运行脚本的用户交换SSH密钥。 看看这个教程

这样做后,您的脚本将无需input密码即可运行。 但是,为了安全起见,你不想为root用户这么做!