如何编写一个Unix脚本以在多个远程服务器上快速启动服务?

问题描述:

我想在多台(〜20台)Unix服务器上运行一个应用程序。我不想单独使用SSH,而是想登录到其中一个,并使用脚本将其全部启动。如何编写一个Unix脚本以在多个远程服务器上快速启动服务?

该应用程序不需要任何直接的用户交互,所以我基本上只需要在每台机器上运行'./app arg1 arg2'。

直接SSH的一个改进是在后台启动SSH会话,然后wait为所有人完成。这样您就可以同时在远程服务器上执行命令。

我们在我们的生产脚本中使用这种技术。

function start_server () 
{ 
    ssh $1 '/path/to/start_service_script' 
} 

echo "Starting servers" 
for serv_name in $(cat /path/to/server-list) 
do 
    # I usually declare a function, because if SSH command 
    # gets more elaborate (especially if it has ampersands 
    # as part of the command, the shell has trouble parsing 
    # the background push (& at the end of the command) 
    # 
    # In this particular case it would be no trouble to 
    # inline ssh here 
    start_server ${serv_name} & 
done 

echo 
# Very important to wait till all the spawned processes finish 
wait 

有一点需要注意,因为所有的子进程同时运行,并使用相同的控制台,您可以在屏幕上看到一些交错输出。

+0

如果您使用斐波纳契树而不是星形拓扑,则可以减少主要主机上的负载,并且还可以加快完成广播传播的时间。尽管如此,+1为'&'主意:) – bitmask

+0

@bitmask。对于大约20台服务器(与OP请求一样),我没有看到*服务器的负载问题。 –

omnissh() { for s in $(cat /server/list) ; do ssh $s "[email protected]" ; done } 

omnissh /etc/init.d/service start 

你将不得不使用ssh,如果设置正确的公共密钥到你的服务器,你就不必输入密码:

for host in hosts 
do 
    ssh [email protected]$host "./app arg1 arg2" 
done 

否则,你可以使用Fabric帮助你以编程方式做到这一点。