如何从 bash shell SSH 到多个服务器并提供完整登录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13670638/
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
How to SSH into multiple servers from bash shell and provide full logins?
提问by IAmYourFaja
This seems to be a pretty popular question, and one that has about 1,000 different answers depending on what forum you look at. Unfortunately, none work for me.
这似乎是一个非常受欢迎的问题,根据您查看的论坛,该问题有大约 1,000 个不同的答案。不幸的是,没有一个对我有用。
I'm trying to write a bash shell script that SSHes into a list of servers and runs a simple stop <x> servicecommand to shutdown application servers on each machine.
我正在尝试编写一个 bash shell 脚本,该脚本通过 SSH 连接到服务器列表并运行一个简单的stop <x> service命令来关闭每台机器上的应用程序服务器。
To do this manually:
要手动执行此操作:
ssh [email protected]
[email protected]'s password: ourpassword
Last login: Fri Nov 30 14:37:51 2012 from <some-ip-addr>
server01:[user@machinename ~]# (now we are SSHed in)
So I ask: given a set name of servers (server01through server25), how can I write a bash script to SSH into all of them and run service ourservice stop? This script should not require any human interaction once kicked off, and so should provide the SSH command with the appropriate password (ourpassword) to use. Furthermore, I need properly exit (or just close connections) after the script SSHes into each server so we don't hang resources (open connections, etc.). Thanks in advance.
所以我问:给定一组服务器名称(server01通过server25),我如何编写一个 bash 脚本以通过 SSH 连接到所有服务器并运行service ourservice stop?此脚本一旦启动就不需要任何人为交互,因此应为 SSH 命令提供适当的密码 ( ourpassword) 以供使用。此外,我需要在脚本 SSH 进入每个服务器后正确退出(或只是关闭连接),这样我们就不会挂起资源(打开连接等)。提前致谢。
回答by misterakko
Do this
做这个
- Make yourself a public/private keypair, using the ssh-keygencommand
- Save your private key in all of your servers, inside the .ssh/authorized_keysfolder
- 使用ssh-keygen命令使自己成为公钥/私钥对
- 将您的私钥保存在所有服务器中的.ssh/authorized_keys文件夹内
Now you can connect to any server without typing a password, which is our first objective here.
现在您无需输入密码即可连接到任何服务器,这是我们在这里的第一个目标。
Now you can send commands to your servers using the following syntax:
现在您可以使用以下语法向您的服务器发送命令:
ssh username@serverid 'command'
There's a nice if short description of this at this page.
在这个页面上有一个很好的简短描述。
So, you just concatenate your 25 commands in a file and fire that up, like this:
因此,您只需将 25 个命令连接到一个文件中并启动它,如下所示:
ssh [email protected] 'service ourservice stop'
ssh [email protected] 'service ourservice stop'

