准备内容:
函数库链接地址:https://mp.csdn.net/mdeditor/89964048#
1.存储远程主机IP地址的文件/cloud_nsd/shell/ip.txt
不用的IP地址需用“#”注释
#201.1.2.100
#201.1.2.200
#192.168.4.6
192.168.4.1
192.168.4.2
2.pssh.sh脚本
#!/bin/bash
#AUTHOR:AN
#VERSION:1.1.0
#DATE:2019-04-16
#MODIFY:2019-05-08 2019-05-15 2019-05-20
#DESCRIBE:ssh免密登陆,并发布NFS共享给远程主机
######################定义变量######################
Nfs_Dir=/cloud_nsd#NFS共享目录
Script_Path=$Nfs_Dir/shell#脚本目录
Soft_Path=$Nfs_Dir/soft#软件目录
Log_Path=$Nfs_Dir/logs/pssh.log#pssh日志路径
Ip_File=$Nfs_Dir/Ip_Temp.txt#存放执行IP
#加载函数库
if [ -f "$Script_Path/myfunction.lib" ];then
source $Script_Path/myfunction.lib
else
echo -e "\033[31m函数库不存在\033[0m"
exit $NOEXIST
fi
grep -v '^#' $Script_Path/ip.txt >$Ip_File#去掉注释,提取/cloud_nsd/shell/ip.txt的有效IP
rpm -q pssh &>/dev/null || rpm -ivh $Soft_Path/lnmp_soft/pssh-2.3.1-5.el7.noarch.rpm &>/dev/nulll
#将本机公钥发送给远程主机
SENDKEY(){
YUM expect
[ ! -f /root/.ssh/id_rsa.pub ] && ssh-keygen -N '' -f /root/.ssh/id_rsa #非交互生成密钥文件
for i in `cat $Ip_File`
do
expect << EOF
set timeout 300
spawn ssh-copy-id root@$i
expect "(yes/no)?"{send "yes\r"}
expect "password:" {send "123456\r"}
expect "#" {send "exit\r"}
EOF
done
}
#批量发送安装包,并解压
PSSH_TAR(){
pscp.pssh -h $Ip_File /cloud_nsd/Install.tar.gz /root#发送我的安装包
pssh -h $Ip_File -e $Log_Path "tar -xPf /root/Install.tar.gz"#解压
}
#搭建NFS服务器,发布/cloud_nsd共享目录
NFS(){
exportfs -rv | grep "$Nfs_Dir" &> /dev/null
if [ $? -ne 0 ];then
YUM nfs-utils#安装nfs软件
echo "$Nfs_Dir *(ro)" >>/etc/exports
STR_SVC nfs-server
exportfs -rv | grep "$Nfs_Dir" &> /dev/null
[ $? -ne 0 ] && ERROR NFS && exit $INSERROR
fi
#在远程主机上挂载本机的NFS
pssh -h $Ip_File -e $Log_Path "mkdir $Nfs_Dir"
pssh -ih $Ip_File -e $Log_Path "mount 192.168.4.254:$Nfs_Dir $Nfs_Dir"
}
#批量执行脚本
EXCUTE_SCRIPT(){
pssh -t 1500 -ih $Ip_File -e $Log_Path "bash $Script_Path/$1 $2 $3 $4" #执行脚本,可以接收位置变量
}
#帮助信息
HELP(){
cat << EOF
pssh.sh version 1.1.0
Usage: pssh.sh [-h] [-p] [-n] [-s 脚本] [-I]
=======================================================================
optional arguments:
-h提供帮助信息
-p发送本机公钥
-n发布NFS共享
-s在远程主机执行脚本
-I发送安装包并解压
EXAMPLE:
pssh.sh -p
pssh.sh -s yum.sh
EOF
}
#############################主程序#############################
clear
[ $# -eq 0 ] && HELP
while getopts :hps:In ARGS
do
case $ARGS in
h)
HELP;;
p)
SENDKEY;;
n)
NFS;;
s)
EXCUTE_SCRIPT $OPTARG $3 $4 $5;;
I)
PSSH_TAR;;
\?)
cecho 31 "Invalid option:bash `basename $0` [-h]"
esac
done