因为工作需要,需要修改集群中机器的配置,一台一台的修改太浪费时间,就想能不能通过自动化脚本批量执行命令,尝试写一个,自己shell不熟悉,写的有点渣渣

if [ "$#" -ne 2 ];then
echo "USAGE:$0 -f host_file cmd"
exit -1
fi
file_name=$1
cmds=$2
filepath=$(cd `dirname $0`; pwd)
host_file="$filepath/$file_name"
if [ ! -e $host_file ];then
echo "$host_file not exit;"
exit 0
fi
cat $host_file | while read line
do
echo $line>>result
ssh -n -p3600 $line source ~/.bash_profile;$cmds >> result
#"source ~/.bash_profile;$cmds" > result
if [ $? -eq 0 ] ; then
echo "host:$line,$cmds done!"
else
echo "host:$line error: " $?
fi
done
执行方式xxxx.sh host_file ‘cmd’

其中xxx.sh是脚本名称,host_file是需要操作机器的ip地址列表,需要可以免密码登陆;cmd是需要操作的命令,如果命令之间存在空格,则需要用引号包起来。

note:
1.ssh和cmd需要写在同一行
2.ssh -n使用本地作为标准输入
Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The ssh program will be put in the background. (This does not work if ssh needs to ask for a password or passphrase; see also the -f option.)