如何从 bash 脚本中 ssh?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1895185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:47:33  来源:igfitidea点击:

How to ssh from within a bash script?

bashssh

提问by Andrew

I am trying to create an ssh connection and do some things on the remote server from within the script.

我正在尝试创建一个 ssh 连接并从脚本中在远程服务器上做一些事情。

However the terminal prompts me for a password, then opens the connection in the terminal window instead of the script. The commands don't get executed until I exit the connection.

但是终端会提示我输入密码,然后在终端窗口而不是脚本中打开连接。在我退出连接之前,不会执行这些命令。

How can I ssh from within a bash script?

如何从 bash 脚本中 ssh?

回答by halfdan

  1. If you want the password prompt to go away then use key based authentication (described here).

  2. To run commands remotely over ssh you have to give them as an argument to ssh, like the following:

  1. 如果您希望密码提示消失,请使用基于密钥的身份验证(此处描述)。

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

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

root@host:~ # ssh root@www 'ps -ef | grep 阿帕奇 | grep -v grep | wc -l'

回答by SiegeX

If you want to continue to use passwords and not use key exchange then you can accomplish this with 'expect' like so:

如果您想继续使用密码而不使用密钥交换,那么您可以使用“expect”来完成此操作,如下所示:

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

回答by Kent Fredric

There's yet another way to do it using Shared Connections, ie: somebody initiates the connection, using a password, and every subsequent connection will multiplex over the same channel, negating the need for re-authentication. ( And its faster too )

还有另一种使用共享连接的方法,即:某人使用密码启动连接,并且每个后续连接都将在同一通道上多路复用,从而无需重新进行身份验证。(而且它也更快)

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

then you just have to log in, and as long as you are logged in, the bash script will be able to open ssh connections.

那么你只需要登录,只要你登录,bash脚本就可以打开ssh连接。

You can then stop your script from working when somebody has not already opened the channel by:

然后,当有人尚未打开频道时,您可以通过以下方式停止脚本工作:

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

回答by Dan Soap

What you need to do is to exchange the SSH keys for the user the script runs as. Have a look at this tutorial

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

After doing so, your scripts will run without the need for entering a password. But, for security's sake, you don't want to do this for root users!

执行此操作后,您的脚本将无需输入密码即可运行。但是,为了安全起见,您不想为 root 用户执行此操作!