目的:在管理多个linux主机时,为了方便运维和使用,我们一般都会打通主机之间的ssh免密码登陆。在主机之间免密码登陆的前提下,我们就可以批量在这些主机上执行命令和分发文件了,下面就是具体shell脚本。
1.分发文件脚本:deploy.sh
#!/bin/bash
#set -x
if [ $# -lt 2 ]
then
echo "Usage: ./ deploy.sh Command MachineTag"
echo "Usage: ./ deploy.sh Command MachineTag confFile"
exit
fi
file=$1
tag=$2
dir=$3
if [ 'a'$4'a' == 'aa' ]
then
confFile=~/bin/deploy.conf
else
confFile=$4
fi
if [ -f $confFile ]
then
for server in `cat $confFile|grep -v '^#'|grep ','$tag','|awk -F',' '{print $1}'`
do
echo "*******************$server***************************"
#ssh $server "source ~/.bash_profile; $cmd"
scp -r $file $server:$3
done
else
echo "Error: Please assign config file or run runRemoteCmd.sh command with deploy.conf in same directory"
fi
2.批量执行命令脚本:runRemoteCmd.sh
#!/bin/bash
#set -x
if [ $# -lt 2 ]
then
echo "Usage: ./runRemoteCmd.sh Command MachineTag"
echo "Usage: ./runRemoteCmd.sh Command MachineTag confFile"
exit
fi
cmd=$1
tag=$2
if [ 'a'$3'a' == 'aa' ]
then
confFile=~/bin/deploy.conf
else
confFile=$3
fi
if [ -f $confFile ]
then
for server in `cat $confFile|grep -v '^#'|grep ','$tag','|awk -F',' '{print $1}'`
do
echo "*******************$server***************************"
ssh $server "source ~/.bash_profile; $cmd"
done
else
echo "Error: Please assign config file or run runRemoteCmd.sh command with deploy.conf in same directory"
fi
3.主机列表文件格式:deploy.conf
10.131.127.1,all,
10.131.127.2,all,
10.131.127.9,all,
10.131.127.10,all,
10.131.127.11,all,
10.131.127.12,all,
4.命令格式:
./runRemoteCmd.sh "ls /root" all deploy.conf
sh deploy.sh /hdfs/data/yinkp/CDH/test/jdk all ~/ deploy.conf