Shell Script集合
Shell Script集合

Shell Script集合

KVM管理脚本(v10.5)

#注意该版本使用到了nc命令,如果没有需要自行安装,使用了红帽的. /etc/init.d/functions,若需要使用Ubunt请删除此行
#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-09-13
#FileName:          install_nginx.sh
#URL:               hhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************
. /etc/init.d/functions

Red="\e[1;31m"
Purple="\e[1;35m"
Green="\e[1;32m"
Blue="\e[1;36m"
Yellow="\e[1;33m"
End="\e[0m"

#克隆集群
clone() {
    lists=virsh list --all |awk '/.*template.*/{print $2}'
    echo "模板清单:"
    echo "<-------------------->"
    for x in  $lists;do
        echo -e "$Purple$x$End"
    done
    echo "<-------------------->"
    read -p "请输入克隆模板: " template
    #read -p "请输入克隆模板ip: " ip
    read -p "请输入集群名称: "  name
    read -p "请输入节点数: "    node
    read -p "请输入ip起点x(y.y.y.x): " num
    read -p "请输入模板IP地址:" tempip
    perip=echo "$tempip" | egrep -o "[0-9]+\.[0-9]+\.[0-9]+\."
    endip=echo $tempip | awk -F"." '{print $NF}'
    echo $perip 
    echo $endip
    for  ((i=0;i<$node;i++)) ;do
         let n=$i+1
         arg[$i]="$name-0$n"
         virt-clone -o $template -n ${arg[$i]}  -f /var/lib/libvirt/images/${arg[$i]}.qcow2 || continue
         virsh start ${arg[$i]} ||  continue
         #sleep 60
	 while true;do
             nc -vz $tempip 22 &> /dev/null && break
	 done
         echo $num ${arg[$i]}
	 if [[ $template =~ "ubuntu" ]];then
             ssh root@$tempip "sed -i -r 's@(^[[:space:]]+- $perip)[0-9]+@\1$num@' /etc/netplan/00-installer-config.yaml;hostnamectl set-hostname ${arg[$i]} ;reboot"  &> /dev/null
         else 
             ssh root@$tempip "sed -i -r 's@(^IPADDR=).*@\1$perip$num@' /etc/sysconfig/network-scripts/ifcfg-eth0;hostnamectl set-hostname ${arg[$i]} ;reboot" &> /dev/null	     
         fi 
         let num=$num+1
    done
}

#删除集群
delete(){
    lists1=virsh  list --all | awk 'NR!=1{print $2}'|sed -nr "s/^(.*)-[0-9]+$/\1/p" |uniq
    echo "<-------------------->"
    for n in $lists1 ;do
	echo -e "$Purple$n$End"
    done
    echo "<-------------------->"
    dname=1
    echo $dname
    read -p "请输入集群名称:"  dname
    echo $danme
    for i in virsh list --all| awk -v dname=$dname '$0 ~ dname{print $2}';do
    echo -e  "$Red$i$End"
    if [[ $i =~ "template" ]]; then
	continue;    
    elif [[ $dname ==  "" ]];then
	action "删除失败" false
       	exit
    else
        virsh destroy $i &> /dev/null
        virsh  undefine --remove-all-storage $i &> /dev/null && action "删除成功" true  || action "删除失败" false 
    fi
    done
}

#单节点启动
nodestart(){
    echo "<-------------------->"
    for m in virsh  list --all | egrep ".*off$"|awk '{print $2}' ;do
        echo -e "$Purple$m$End"
    done
    echo "<-------------------->"
    read -p "请输入节点名称:"  startnode
    virsh start $startnode &> /dev/null &&  action "$startnode 节点启动成功" true || action "$startnode 节点启动失败" false
}

#单节点重启
noderestart(){
    echo "<-------------------->"
    for o in virsh  list --all | egrep ".*running$"|awk '{print $2}' ;do
        echo -e "$Purple$o$End"
    done
    echo "<-------------------->"
    read -p "请输入节点名称:"  restartnode
    virsh reboot $restartnode &> /dev/null &&  action "$restartnode 节点重启成功" true || action "$restartnode 节点重启失败" false
}

#单节点关机
nodestop(){
    echo "<-------------------->"
    for p in virsh  list --all | egrep ".*running$"|awk '{print $2}' ;do
        echo -e "$Purple$p$End"
    done
    echo "<-------------------->"
    read -p "请输入节点名称:"  stopnode
    virsh shutdown $stopnode &> /dev/null &&  action "$stopnode 节点关机成功" true || action "$stopnode 节点关机失败" false
}

#启动集群
clusterstart(){
    lists2=virsh  list --all | awk 'NR!=1{print $2}'|sed -nr "s/^(.*)-[0-9]+$/\1/p"|sort -nr|uniq
    echo "<-------------------->"
    for q in $lists2 ;do
        echo -e "$Purple$q$End"
    done
    echo "<-------------------->"
    read -p "请输入集群名称:"  dname
    for i1 in virsh list --all| awk -v dname=$dname '$0 ~ dname{print $2}';do
    echo -e  "$Red$i1$End"
    virsh start $i1 &> /dev/null &&  action "$i1 节点启动成功" true || action "$i1 节点启动失败" false
    done

}

#关闭集群
clusterstop(){
    lists3=virsh  list --all | awk 'NR!=1{print $2}'|sed -nr "s/^(.*)-[0-9]+$/\1/p" |sort -nr|uniq
    echo "<-------------------->"
    for r in $lists3 ;do
        echo -e "$Purple$r$End"
    done
    echo "<-------------------->"
    read -p "请输入集群名称:"  dname
    for i2 in virsh list --all| awk -v dname=$dname '$0 ~ dname{print $2}';do
    echo -e  "$Red$i2$End"
    virsh shutdown $i2 &> /dev/null &&  action "$i2 节点关闭成功" true || action "$i2 节点关闭失败" false
    done
}

#集群重启
clusterrestart(){
    lists4=virsh  list --all | awk 'NR!=1{print $2}'|sed -nr "s/^(.*)-[0-9]+$/\1/p" | sort -nr|uniq
    echo "<-------------------->"
    for s in $lists4 ;do
        echo -e "$Purple$s$End"
    done
    echo "<-------------------->"
    read -p "请输入集群名称:"  dname
    for i3 in virsh list --all| awk -v dname=$dname '$0 ~ dname{print $2}';do
    echo -e  "$Red$i3$End"
    virsh reboot $i3 &> /dev/null &&  action "$i3 节点重启成功" true || action "$i3 节点重启失败" false
    done

}


#单机克隆
clone_Single(){
    echo "<-------------------->"
    for p in virsh list --all |awk '/.*template.*/{print $2}' ;do
        echo -e "$Purple$p$End"
    done
    echo "<-------------------->"
    read -p "请输入克隆模板: " templatecs
    #read -p "请输入克隆模板ip: " ip
    read -p "请输入名称: " csname
    read -p "请输入ipx(y.y.y.x): " num1
         virt-clone -o $templatecs -n $csname  -f /var/lib/libvirt/images/$csname.qcow2 || continue
         virsh start $csname ||  continue
         sleep 60
         echo $csname
         if [[ $templatecs =~ "ubuntu" ]];then
             ssh root@10.0.0.100 "sed -i -r 's@(^[[:space:]]+- 10.0.0.)[0-9]+@\1$num1@' /etc/netplan/00-installer-config.yaml;hostnamectl set-hostname $csname ;reboot"
         else
             ssh root@192.168.100.10 "sed -i -r 's@(^IPADDR=).*@\1192.168.10.$num1@' /etc/sysconfig/network-scripts/ifcfg-eth0;hostnamectl set-hostname $csname ;reboot"
         fi
}

#单机删除
delete_Single(){
    echo "<-------------------->"
    for p in virsh  list --all |awk '{print $2}' ;do
        echo -e "$Purple$p$End"
    done
    echo "<-------------------->"
    read -p "请输入机器名称:"  dsname
    echo $dsname
    if [[ $i =~ "template" ]]; then
        exit;
    elif [[ $dsname ==  "" ]];then
        action "删除失败" false
        exit
    else
        virsh  destroy $dsname &> /dev/null
        virsh  undefine --remove-all-storage $dsname &> /dev/null && action "删除成功" true  || action "删除失败" false
    fi

}

#创建快照
create_snapshot(){
    echo "<-------------------->"
    for p in virsh  list --all |awk '{print $2}' ;do
        echo -e "$Purple$p$End"
    done
    echo "<-------------------->"
    read -p "请选择你要创建快照的机器:" shname
    virsh snapshot-list $shname
    read -p "请输入创建的快照名称:" createsnap
    virsh snapshot-create-as $shname $createsnap  && echo -e "$Blue 创建成功  $End"  || echo -e "$Red 创建失败 $End"
    virsh snapshot-list $shname
}


#删除快照
delete_snapshot(){
    echo "<-------------------->"
    for p in virsh  list --all |awk '{print $2}' ;do
        echo -e "$Purple$p$End"
    done
    echo "<-------------------->"
    read -p "请输入你要删除快照的机器:" dshname
    virsh snapshot-list $dshname
    read -p "请输入删除的快照名称:" deletesnap
    virsh snapshot-delete $dshname $deletesnap && echo -e "$Blue 删除成功  $End"  || echo -e "$Red 删除失败 $End"
    virsh snapshot-list $dshname
}


#恢复快照
recover_snapshot(){
    echo "<-------------------->"
    for p in virsh  list --all |awk '{print $2}' ;do
        echo -e "$Purple$p$End"
    done
    echo "<-------------------->"
    read -p "请输入你要恢复快照的机器:" rshname
    virsh snapshot-list $rshname
    read -p "请输入恢复的快照名称:" recoversnap
    virsh snapshot-revert $rshname  $recoversnap  && echo -e "$Blue 恢复成功  $End"  || echo -e "$Red 恢复失败 $End"
    virsh snapshot-list $rshname
}


virsh list --all
PS3="请按要求输入操作选项:"
select lists in  克隆集群 删除集群 启动集群 关闭集群 集群重启  单节点启动 单节点关机  单节点重启   克隆单机  单机删除 创建快照  删除快照  恢复快照   退出;do
case $REPLY in     #  1       2       3        4        5          6          7           8           9         10       11        12        13
1)
    echo -e "$Blue$lists$End"
    clone
    ;;
2)  
    echo -e "$Red$lists$End"
    delete
    ;;
3)  
    echo -e "$Green$lists$End"
    clusterstart
    ;;
4)
    echo -e "$Red$lists$End"
    clusterstop
    ;;
5)
    echo -e "$Yellow$lists$End"
    clusterrestart
    ;;
6)
    echo -e "$Green$lists$End"
    nodestart
    ;;
7)
    echo -e "$Red$lists$End"
    nodestop
    ;;
8)
    echo -e "$Yellow$lists$End"
    noderestart
    ;;

9)
    echo -e "$Blue$lists$End"
    clone_Single
    ;;
10)
    echo -e "$Blue$lists$End"
    delete_Single
    ;;
11)
    echo -e "$Blue$lists$End"
    create_snapshot
    ;;
12)
    echo -e "$Blue$lists$End"
    delete_snapshot
    ;;
13)
    echo -e "$Blue$lists$End"
    recover_snapshot
    ;;
14)
    echo -e "$Blue$lists$End"
    exit
    ;;
*)
    echo -e "$Red输入错误$End"
    ;;
esac
done

自动安装JDK_TOMCAT脚本(v1.0)

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-09-22
#FileName:          install_jdk_tomcat.sh
#URL:               hhhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************
#JDK_FILE="jdk-8u333-linux-x64.tar.gz"
#TOMCAT_FILE="apache-tomcat-9.0.64.tar.gz"
JDK_DIR="/usr/local"
TOMCAT_DIR="/usr/local"
DIR=pwd

color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$2" && $MOVE_TO_COL
    echo -n "["
    if [ $1 = "success" -o $1 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "    
    elif [ $1 = "failure" -o $1 = "1"  ] ;then
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo                                                                                                                              
}



install_jdk(){

echo $JDK_FILE
if !  [  -f "$DIR/$JDK_FILE" ];then
    color 1 "$JDK_FILE 文件不存在" 
    exit; 
elif [ -d $JDK_DIR/jdk ];then
    color 1  "JDK 已经安装" 
    exit
else 
    [ -d "$JDK_DIR" ] || mkdir -pv $JDK_DIR
fi
tar xvf $DIR/$JDK_FILE  -C $JDK_DIR
cd  $JDK_DIR && ln -s jdk* jdk 

cat >  /etc/profile.d/jdk.sh <<EOF
export JAVA_HOME=$JDK_DIR/jdk
export PATH=\$PATH:\$JAVA_HOME/bin
#export JRE_HOME=\$JAVA_HOME/jre
#export CLASSPATH=.:\$JAVA_HOME/lib/:\$JRE_HOME/lib/
EOF
. /etc/profile.d/jdk.sh
java -version && color 0 "JDK 安装完成" || { color 1  "JDK 安装失败" ; exit; }

}

install_tomcat(){
if ! [ -f "$DIR/$TOMCAT_FILE" ];then
    color 1 "$TOMCAT_FILE 文件不存在" 
    exit; 
elif [ -d $TOMCAT_DIR/tomcat ];then
    color 1 "TOMCAT 已经安装" 
    exit
else 
    [ -d "$TOMCAT_DIR" ] || mkdir -pv $TOMCAT_DIR
fi
tar xf $DIR/$TOMCAT_FILE -C $TOMCAT_DIR
cd  $TOMCAT_DIR && ln -s apache-tomcat-*/  tomcat
echo "PATH=$TOMCAT_DIR/tomcat/bin:"'$PATH' > /etc/profile.d/tomcat.sh
id tomcat &> /dev/null || useradd -r -s /sbin/nologin tomcat

cat > $TOMCAT_DIR/tomcat/conf/tomcat.conf <<EOF
JAVA_HOME=$JDK_DIR/jdk
EOF

chown -R tomcat.tomcat $TOMCAT_DIR/tomcat/

cat > /lib/systemd/system/tomcat.service  <<EOF
[Unit]
Description=Tomcat
#After=syslog.target network.target remote-fs.target nss-lookup.target
After=syslog.target network.target 

[Service]
Type=forking
EnvironmentFile=$TOMCAT_DIR/tomcat/conf/tomcat.conf
ExecStart=$TOMCAT_DIR/tomcat/bin/startup.sh
ExecStop=$TOMCAT_DIR/tomcat/bin/shutdown.sh
RestartSec=3
PrivateTmp=true
User=tomcat
Group=tomcat

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now tomcat.service &> /dev/null
systemctl is-active tomcat.service &> /dev/null &&  color 0 "TOMCAT 安装完成" || { color 1 "TOMCAT 安装失败" ; exit; }

}




PS3="请按要求输入操作选项:"
select lists in 离线安装Oracle-JDK 离线安装Tomcat 退出;do
case $REPLY in
1)
    echo -e "$Blue$lists$End"
    read -p "请输入JDK文件名称(例如:jdk-8u333-linux-x64.tar.gz):" JDK_FILE
    install_jdk 
    ;;
2)  
    echo -e "$Blue$lists$End"
    read -p "请输入Tomcat文件名称(例如:apache-tomcat-9.0.64.tar.gz):" TOMCAT_FILE
    install_tomcat
    ;;
3)
    echo -e "$Blue$lists$End"
    exit
    ;;
*)
    echo -e "$Red输入错误$End"
    ;;
esac
done

自动安装nexus脚本(v1.0)

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-09-27
#FileName:          install_nexus.sh
#URL:               hhhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************
#NEXUS_URL="https://download.sonatype.com/nexus/3/nexus-3.39.0-01-unix.tar.gz"
#NEXUS_URL="https://download.sonatype.com/nexus/3/nexus-3.36.0-01-unix.tar.gz"
#NEXUS_URL="https://download.sonatype.com/nexus/3/nexus-3.29.2-02-unix.tar.gz"
INSTALL_DIR=/usr/local/nexus

HOST=hostname -I|awk '{print $1}'
GREEN="echo -e \E[32;1m"
END="\E[0m"

. /etc/os-release

color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$1" && $MOVE_TO_COL
    echo -n "["
    if [ $2 = "success" -o $2 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "    
    elif [ $2 = "failure" -o $2 = "1"  ] ;then 
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo 
}



install_nexus() {
    wget -P /usr/local/src/ $NEXUS_URL || { color  "下载失败!" 1 ;exit ; }
    tar xf /usr/local/src/${NEXUS_URL##*/} -C /usr/local
    ln -s /usr/local/nexus-*/ ${INSTALL_DIR}
    ln -s ${INSTALL_DIR}/bin/nexus /usr/bin/
}

start_nexus (){
cat   > /lib/systemd/system/nexus.service <<EOF
[Unit]
Description=nexus service
After=network.target

[Service]
Type=forking
LimitNOFILE=65536
ExecStart=${INSTALL_DIR}/bin/nexus start
ExecStop=${INSTALL_DIR}/bin/nexus stop
User=root
#User=nexus
Restart=on-abort

[Install]
WantedBy=multi-user.target

EOF
    systemctl daemon-reload 
    systemctl enable --now  nexus.service
    if [ $? -eq 0 ] ;then 
        color "nexus 安装成功" 0  
    echo "-------------------------------------------------------------------"
        echo -e "访问链接: \c"
    ${GREEN}"http://$HOST:8081/"${END}
    while [ ! -f ${INSTALL_DIR}/../sonatype-work/nexus3/admin.password ];do
        sleep 1
    done
    PASS=cat ${INSTALL_DIR}/../sonatype-work/nexus3/admin.password
    echo -e "用户和密码: \c"
    ${GREEN}"admin/$PASS"$END
    else 
        color "nexus 安装失败!" 1
        exit 1
    fi 
}


install_nexus_outline(){
    if [  -e $1 ];then
        cp $1  /usr/local/src
    else
         { color  "找不到文件!" 1 ;exit ; }
    fi
    tar xf /usr/local/src/$1 -C /usr/local
    ln -s /usr/local/nexus-*/ ${INSTALL_DIR}
    ln -s ${INSTALL_DIR}/bin/nexus /usr/bin/
}

PS3="请按要求输入操作选项:"
select lists in 在线线安装Nexus 离线安装Nexus 退出;do
case $REPLY in
1)
    echo -e "$Blue$lists$End"
    read -p "请输入下载地址:" NEXUS_URL
    install_nexus
    start_nexus
    ;;
2)  
    echo -e "$Blue$lists$End"
    read -p "请输入文件名称(例如:nexus-3.41.1-01-unix.tar):" NEXUS
    install_nexus_outline $NEXUS
    start_nexus
    ;;
3)
    echo -e "$Blue$lists$End"
    exit
    ;;
*)
    echo -e "$Red输入错误$End"
    ;;
esac
done

自动安装nginx和平滑升级脚本(v1.0)

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-09-13
#FileName:          install_nginx.sh
#URL:               hhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************

Red="\e[1;31m"
Purple="\e[1;35m"
Green="\e[1;32m"
Blue="\e[1;36m"
Yellow="\e[1;33m"
End="\e[0m"

#NGINX_FILE=nginx-1.22.0
#NGINX_FILE=nginx-1.20.2
#NGINX_FILE=nginx-1.18.0
NGINX_URL=http://nginx.org/download/
TAR=.tar.gz
SRC_DIR=/usr/local/src
NGINX_INSTALL_DIR=/apps/nginx
CPUS=lscpu |awk '/^CPU\(s\)/{print $2}'
. /etc/os-release


color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$1" && $MOVE_TO_COL
    echo -n "["
    if [ $2 = "success" -o $2 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "    
    elif [ $2 = "failure" -o $2 = "1"  ] ;then 
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo 
}


check () {
    [ -e ${NGINX_INSTALL_DIR} ] && { color "nginx 已安装,请卸载后再安装" 1; exit; }
    cd  ${SRC_DIR}
    if [  -e ${NGINX_FILE}${TAR} ];then
        color "相关文件已准备好" 0
    else
        color '开始下载 nginx 源码包' 0
        wget ${NGINX_URL}${NGINX_FILE}${TAR} 
        [ $? -ne 0 ] && { color "下载 ${NGINX_FILE}${TAR}文件失败" 1; exit; } 
    fi
} 

install () {
    color "开始安装 nginx" 0
    if id nginx  &> /dev/null;then
        color "nginx 用户已存在" 1 
    else
        useradd -s /sbin/nologin -r  nginx
        color "创建 nginx 用户" 0 
    fi
    color "开始安装 nginx 依赖包" 0
    if [ $ID == "centos" ] ;then
        if [[ $VERSION_ID =~ ^7 ]];then
            yum -y  install  gcc  make pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
        elif [[ $VERSION_ID =~ ^8 ]];then
            yum -y  install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed 
        else 
            color '不支持此系统!'  1
            exit
        fi
    elif [ $ID == "rocky"  ];then
        yum -y  install gcc make gcc-c++ libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel perl-ExtUtils-Embed 
    else
        apt update
        apt -y install gcc make  libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev
    fi
    cd $SRC_DIR
    tar xf ${NGINX_FILE}${TAR}
    NGINX_DIR=echo ${NGINX_FILE}${TAR}| sed -nr 's/^(.*[0-9]).*/\1/p'
    cd ${NGINX_DIR}
    ./configure --prefix=${NGINX_INSTALL_DIR} --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module 
    make -j $CPUS && make install 
    [ $? -eq 0 ] && color "nginx 编译安装成功" 0 ||  { color "nginx 编译安装失败,退出!" 1 ;exit; }
    chown -R nginx.nginx ${NGINX_INSTALL_DIR}
    echo "PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/nginx.sh
    cat > /lib/systemd/system/nginx.service <<EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=/bin/rm -f ${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=${NGINX_INSTALL_DIR}/sbin/nginx -t
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx
ExecReload=/bin/kill -s HUP \$MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
LimitNOFILE=100000

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable --now nginx &> /dev/null 
    systemctl is-active nginx &> /dev/null ||  { color "nginx 启动失败,退出!" 1 ; exit; }
    color "nginx 安装完成" 0
}   
update(){
    cd ~
    wget ${NGINX_URL}${NGINX_FILE_NEW}${TAR}
    tar xf ${NGINX_FILE_NEW}${TAR}
    #nginx=which nginx
    nginx -V &> config
    config=cat config | grep -e "^c"| cut -d ":" -f2
    cd ${NGINX_FILE_NEW}
    ./configure $config
    make
    cp /apps/nginx/sbin/nginx /opt/nginx.old
    cp -f ./objs/nginx /apps/nginx/sbin/
    /apps/nginx/sbin/nginx -t
    kill -USR2 cat /apps/nginx/run/nginx.pid
    kill -WINCH cat /apps/nginx/run/nginx.pid.oldbin
    kill -QUIT cat /apps/nginx/run/nginx.pid.oldbin
    
}

PS3="请按要求输入操作选项:"
select lists in  编译安装nginx 在线升级 退出;do
case $REPLY in
1)
    echo -e "$Blue$lists$End"
    read -p "请输入nginx版本(例如:nginx-1.22.0):" NGINX_FILE
    check
    install
    ;;
2)  
    echo -e "$Blue$lists$End"
    read -p "请输入新的nginx版本(例如:nginx-1.22.0):" NGINX_FILE_NEW
    #check
    update
    ;;
3)
    echo -e "$Blue$lists$End"
    exit
    ;;
*)
    echo -e "$Red输入错误$End"
    ;;
esac
done

自动安装docker脚本(v1.0)

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-10-14
#FileName:          install_docker.sh
#URL:               hhhhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************
DOCKER_VERSION=20.10.19
#URL=https://mirrors.aliyun.com
URL=https://download.docker.com

prepare () {
    if [ ! -e docker-${DOCKER_VERSION}.tgz ];then
        #wget ${URL}/docker-ce/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz
        wget ${URL}/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz
    fi
    [ $? -ne 0  ] && { echo "文件下载失败"; exit; }
}

install_docker () {
    tar xf docker-${DOCKER_VERSION}.tgz -C /usr/local/
    cp /usr/local/docker/* /usr/bin/
    cat > /lib/systemd/system/docker.service <<-EOF
[Unit]
Description=Docker Application Container Engine
Documentation=https://docs.docker.com
After=network-online.target firewalld.service
Wants=network-online.target

[Service]
Type=notify
# the default is not to use systemd for cgroups because the delegate issues still
# exists and systemd currently does not support the cgroup feature set required
# for containers run by docker
ExecStart=/usr/bin/dockerd -H unix://var/run/docker.sock
ExecReload=/bin/kill -s HUP \$MAINPID
# Having non-zero Limit*s causes performance problems due to accounting overhead
# in the kernel. We recommend using cgroups to do container-local accounting.
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
# Uncomment TasksMax if your systemd version supports it.
# Only systemd 226 and above support this version.
#TasksMax=infinity
TimeoutStartSec=0
# set delegate yes so that systemd does not reset the cgroups of docker containers
Delegate=yes
# kill only the docker process, not all processes in the cgroup
KillMode=process
# restart the docker process if it exits prematurely
Restart=on-failure
StartLimitBurst=3
StartLimitInterval=60s

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
}

start_docker (){
    systemctl enable --now docker
    docker info
}

config_docker () {
    mkdir -p /etc/docker
    tee /etc/docker/daemon.json <<-'EOF'
    {
      "registry-mirrors": ["https://si7y70hh.mirror.aliyuncs.com"]
     }
EOF
    systemctl restart docker
}

prepare
install_docker
config_docker
start_docker

安装mysql脚本(v.1.0)(目前适用rocky8)

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-08-22
#FileName:          install_mysql.sh
#URL:               hhhhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************
. /etc/init.d/functions

Red="\e[1;31m"
Purple="\e[1;35m"
Green="\e[1;32m"
Blue="\e[1;36m"
Yellow="\e[1;33m"
End="\e[0m"
 
#检查当前登录用户是否是root
check_root(){
if [ $UID -ne 0 ]; then
    action "当前用户不是root,安装失败" false
    exit 1
fi
}

#检查是否已安装了mysql
check_mysql(){
if [  -e /usr/local/mysql ];then
   action "数据库已存在,安装失败" false
   exit 1
fi
}

#本地安装
install(){
   #echo $1
   base=$(echo "$1" | sed -nr "s@(.*).tar.xz@\1@p")
   #echo $base
   groupadd mysql 
   useradd -r -g mysql -s /sbin/nologin mysql   
   mkdir /data/mysql 
   chown mysql:mysql /data/mysql 
   tar xf $1 -C /usr/local/ 
   cd /usr/local/ 
   ln -s $base mysql 
   chown -R root:root /usr/local/mysql/ 
   echo "PATH=/usr/local/mysql/bin:$PATH" > /etc/profile.d/mysql.sh && . /etc/profile.d/mysql.sh
   echo -ne "[mysqld]
datadir=/data/mysql
skip_name_resolve=1
socket=/data/mysql/mysql.sock        
log-error=/data/mysql/mysql.log
pid-file=/data/mysql/mysql.pid
[client]
socket=/data/mysql/mysql.sock"   > /etc/my.cnf 
   mysqld --initialize --user=mysql --datadir=/data/mysql   
   cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld 
   chkconfig --add mysqld 
   chkconfig --list 
   service mysqld start
   passwd=$(awk '/temporary password/{print $NF}' /data/mysql/mysql.log)
   echo $passwd
   mysqladmin -uroot -p"$passwd" password 123456
}

#离线安装
locali(){
   ffile=$(find / -name "$1" )
   echo $ffile
if [ ! -e  "$ffile" ];then
   action "找不到文件$1,请重新输入" false
   exit 1
fi
}

#src=https://downloads.mysql.com/archives/get/p/23/file/mysql-8.0.28-linux-glibc2.12-x86_64.tar.xz
#在线安装
net(){
   cd /data/
   wget $1
   name=$(echo "$1" |awk -F "/" '{print $NF}')
   tar xf $name -C /usr/local/
}


PS3="请按要求输入操作选项:"
select lists in  离线安装MYSQL 在线安装MYSQL 退出;do
case $REPLY in
1)
    echo -e "$Blue$lists$End"
    #read -p "请输入安装文件路径:" file
    check_root
    check_mysql
    read -p "请输入安装文件名:" file
    locali $file
    install $file
    ;;
2)  
    echo -e "$Blue$lists$End"
    check_root
    check_mysql
    read -p "请输入安装链接:" src
    name=$(echo "$src" |awk -F "/" '{print $NF}')
    echo $name
    net $src
    path=/data/path
    install $name
    ;;
3)
    echo -e "$Blue$lists$End"
    exit
    ;;
*)
    echo -e "$Red输入错误$End"
    ;;
esac
done

mysql冷备脚本(v1.0)

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-08-31
#FileName:          mysql-back.sh
#URL:               hhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************

. /etc/rc.d/init.d/functions

remoteIP="10.0.0.154"
binlogpath="/var/lib/mysql/"
myqlpath="/data/mysqllog/"
backpath="/data/date +%F-%H_%M_%S"

lock(){
if [ -e /tmp/mysql.lock ];then 
   exit 1
else
   touch /tmp/mysql.lock
fi
}

unlock(){
rm -rf /tmp/mysql.lock
}

backup(){
lock
ssh root@${remoteIP} "mkdir $backpath"
systemctl stop mysqld.service &> /dev/null
tar czf mysql-data.bak.tar.gz ${binlogpath}* &> /dev/null
tar czf mysqlbinlog.tar.gz ${msqlpath}*  &> /dev/null
scp mysql-data.bak.tar.gz  ${remoteIP}:$backpath  &> /dev/null
scp mysqlbinlog.tar.gz ${remoteIP}:$backpath      &> /dev/null
scp /etc/my.cnf ${remoteIP}:$backpath    &> /dev/null
systemctl start mysqld.service && unlock || action "启动失败" false
}
backup

mysql热备脚本(v1.0)

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-09-01
#FileName:          mysqldump.sh
#URL:               hhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************
. /etc/rc.d/init.d/functions
backpath="/data/date +%F-%H_%M_%S/"
remoteIP='10.0.0.154'

lock(){
if [ -e /tmp/mysql.lock ];then 
   exit 1
else
   touch /tmp/mysql.lock
fi
}

unlock(){
rm -rf /tmp/mysql.lock
}

backup(){
lock
mkdir ${backpath} &> /dev/null
for db in mysql -uroot -e 'show databases' | grep -Ewv '^(Database|information_schema|performance_schema|sys)$';do 
   mysqldump -B $db -F -E -R --triggers --single-transaction --source-data=2 --flush-privileges --default-character-set=utf8mb4 --hex-blob | gzip > ${backpath}$db.sql.gz &> /dev/null
done

tar czf ${backpath}mysqldump.tar.gz ${backpath}* &> /dev/null
key1=md5sum ${backpath}mysqldump.tar.gz |awk '{print $1}'
scp ${backpath}mysqldump.tar.gz root@10.0.0.154: &> /dev/null
key2=ssh root@$remoteIP "md5sum mysqldump.tar.gz" | awk '{print $1}'

if [ $key1 == $key2 ];then
   unlock
else
   action "传输中文件缺失,请确认" false
   exit 1
fi
}
backup

自动安装redis脚本

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-10-29
#FileName:          install_redis.sh
#URL:               hhhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************
#redis-7.0.5.tar.gz
REDIS_VERSION=redis-7.0.5
#REDIS_VERSION=redis-7.0.3
#REDIS_VERSION=redis-6.2.6
#REDIS_VERSION=redis-5.0.14
#REDIS_VERSION=redis-4.0.14
REDIS_URL=http://download.redis.io/releases
PASSWORD=123456
INSTALL_DIR=/apps/redis


CPUS=lscpu |awk '/^CPU\(s\)/{print $2}'
. /etc/os-release

color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$1" && $MOVE_TO_COL
    echo -n "["
    if [ $2 = "success" -o $2 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "    
    elif [ $2 = "failure" -o $2 = "1"  ] ;then 
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo 
}


prepare(){
    if [ $ID = "centos" -o $ID = "rocky" ];then
        yum  -y install gcc make jemalloc-devel systemd-devel
    else
        apt update 
        apt -y install  gcc make libjemalloc-dev libsystemd-dev
    fi
    if [ $? -eq 0 ];then
        color "安装软件包成功"  0
    else
        color "安装软件包失败,请检查网络配置" 1
        exit
    fi
}
install() {   
    if [ ! -f ${REDIS_VERSION}.tar.gz ];then
        wget ${REDIS_URL}/${REDIS_VERSION}.tar.gz || { color "Redis 源码下载失败" 1 ; exit; }
    fi
    tar xf ${REDIS_VERSION}.tar.gz -C /usr/local/src
    cd /usr/local/src/${REDIS_VERSION}
    make -j $CUPS USE_SYSTEMD=yes PREFIX=${INSTALL_DIR} install && color "Redis 编译安装完成" 0 || { color "Redis 编译安装失败" 1 ;exit ; }

    ln -s ${INSTALL_DIR}/bin/redis-*  /usr/bin/
    
    mkdir -p ${INSTALL_DIR}/{etc,log,data,run}
  
    cp redis.conf  ${INSTALL_DIR}/etc/

    sed -i -e 's/bind 127.0.0.1/bind 0.0.0.0/'  -e "/# requirepass/a requirepass $PASSWORD"  -e "/^dir .*/c dir ${INSTALL_DIR}/data/"  -e "/logfile .*/c logfile ${INSTALL_DIR}/log/redis-6379.log"  -e  "/^pidfile .*/c  pidfile ${INSTALL_DIR}/run/redis_6379.pid" ${INSTALL_DIR}/etc/redis.conf


    if id redis &> /dev/null ;then 
         color "Redis 用户已存在" 1 
    else
         useradd -r -s /sbin/nologin redis
         color "Redis 用户创建成功" 0
    fi

    chown -R redis.redis ${INSTALL_DIR}

    cat >> /etc/sysctl.conf <<EOF
net.core.somaxconn = 1024
vm.overcommit_memory = 1
EOF
    sysctl -p 
    if [ $ID = "centos" -o $ID = "rocky" ];then
        echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.d/rc.local
        chmod +x /etc/rc.d/rc.local
        /etc/rc.d/rc.local 
    else 
        echo -e '#!/bin/bash\necho never > /sys/kernel/mm/transparent_hugepage/enabled' >> /etc/rc.local
        chmod +x /etc/rc.local
        /etc/rc.local
    fi


cat > /lib/systemd/system/redis.service <<EOF
[Unit]
Description=Redis persistent key-value database
After=network.target

[Service]
ExecStart=${INSTALL_DIR}/bin/redis-server ${INSTALL_DIR}/etc/redis.conf --supervised systemd
ExecStop=/bin/kill -s QUIT \$MAINPID
Type=notify
User=redis
Group=redis
RuntimeDirectory=redis
RuntimeDirectoryMode=0755
LimitNOFILE=1000000

[Install]
WantedBy=multi-user.target

EOF
     systemctl daemon-reload 
     systemctl enable --now  redis &> /dev/null 
     if [ $? -eq 0 ];then
         color "Redis 服务启动成功,Redis信息如下:"  0 
     else
         color "Redis 启动失败" 1 
         exit
     fi
     sleep 2
     redis-cli -a $PASSWORD INFO Server 2> /dev/null
}

prepare 

install 

自动安装keepalived脚本

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-10-26
#FileName:          install_keepalived.sh
#URL:               hhhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************
KEEPALIVED_VERSION=2.2.7
#KEEPALIVED_VERSION=2.2.2
#KEEPALIVED_VERSION=2.0.20
KEEPALIVED_FILE=keepalived-${KEEPALIVED_VERSION}.tar.gz

KEEPALIVED_INSTALL_DIR=/apps/keepalived
SRC_DIR=/usr/local/src
KEEPALIVED_URL=https://keepalived.org/software/

CPUS=grep -c processor  /proc/cpuinfo

. /etc/os-release


color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$1" && $MOVE_TO_COL
    echo -n "["
    if [ $2 = "success" -o $2 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "    
    elif [ $2 = "failure" -o $2 = "1"  ] ;then 
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo 
}


download_file (){
    cd  ${SRC_DIR}
    if [ $ID = 'centos' -o $ID = 'rocky' ];then
        rpm -q wget &> /dev/null || yum -y install wget 
    elif [ $ID = 'ubuntu' ];then
        dpkg -l |grep wget || { apt update;  apt install -y wget; } 
    else
        color "不支持此操作系统,退出!" 1
        exit
    fi
    if [ ! -e ${KEEPALIVED_FILE} ];then
        wget --no-check-certificate  ${KEEPALIVED_URL}${KEEPALIVED_FILE} 
        [ $? -ne 0 ] && { color "KEEPALIVED源码包下载失败" 1 ; exit; }
    fi
}

install_keepalived () {
    if [ $ID = 'centos' -o $ID = 'rocky' ];then
        yum -y install make gcc ipvsadm autoconf automake openssl-devel libnl3-devel iptables-devel net-snmp-devel glib2-devel pcre2-devel  libmnl-devel systemd-devel &> /dev/null
    elif [ $ID = 'ubuntu' ];then
        apt update 
        apt -y install make gcc ipvsadm build-essential pkg-config automake autoconf libipset-dev libnl-3-dev libnl-genl-3-dev libssl-dev libxtables-dev libip4tc-dev libip6tc-dev libipset-dev libmagic-dev libsnmp-dev libglib2.0-dev libpcre2-dev libnftnl-dev libmnl-dev libsystemd-dev
    else
        color "不支持此操作系统,退出!" 1
    fi
    tar xf ${KEEPALIVED_FILE}
    cd keepalived-${KEEPALIVED_VERSION}
    ./configure --prefix=${KEEPALIVED_INSTALL_DIR} --disable-fwmark
    make -j $CPUS && make install
    if [ $? -eq 0 ];then
        color "KEEPALIVED编译安装成功" 0
    else
        color "KEEPALIVED编译安装失败,退出!" 1
        exit
    fi
    [ -d /etc/keepalived ] || mkdir -p /etc/keepalived
    cp ${KEEPALIVED_INSTALL_DIR}/etc/keepalived/keepalived.conf.sample  /etc/keepalived/keepalived.conf
    cp ./keepalived/keepalived.service /lib/systemd/system/
}

start_keepalived () {
    systemctl daemon-reload
    systemctl enable --now keepalived &> /dev/null 
    systemctl is-active keepalived
    if [ $? -eq 0 ] ;then
        color "Keepalived 服务安装成功!" 0  
    else
        color "Keepalived 服务安装失败!" 1
        exit 1
    fi
}

download_file

install_keepalived

start_keepalived

自动安装haproxy脚本

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-10-21
#FileName:          install_haproxy.sh
#URL:               hhhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************

read -p "请输入haproxy版本(2.6.6):" HAPROXY_VERSION
#HAPROXY_VERSION=2.6.6
HAPROXY_FILE=haproxy-${HAPROXY_VERSION}.tar.gz
#HAPROXY_FILE=haproxy-2.2.12.tar.gz
LUA_VERSION=5.4.4
LUA_FILE=lua-${LUA_VERSION}.tar.gz
#LUA_FILE=lua-5.4.3.tar.gz
HAPROXY_INSTALL_DIR=/apps/haproxy

SRC_DIR=/usr/local/src
CWD=pwd
CPUS=lscpu |awk '/^CPU\(s\)/{print $2}'
LOCAL_IP=$(hostname -I|awk '{print $1}')

STATS_AUTH_USER=admin
STATS_AUTH_PASSWORD=123456

VIP=192.168.10.100
MASTER1=192.168.10.101
MASTER2=192.168.10.102
MASTER3=192.168.10.103

. /etc/os-release

color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$1" && $MOVE_TO_COL
    echo -n "["
    if [ $2 = "success" -o $2 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "    
    elif [ $2 = "failure" -o $2 = "1"  ] ;then 
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo 
}


check_file (){
    if [ ! -e ${LUA_FILE} ];then
        color "缺少${LUA_FILE}文件!" 1
        exit
    elif [ ! -e ${HAPROXY_FILE} ];then
        color "缺少${HAPROXY_FILE}文件!" 1
        exit
    else
        color "相关文件已准备!" 0
    fi
}

install_packs () {
    if [ $ID = "centos" -o $ID = "rocky" ];then
        yum -y install gcc make gcc-c++ glibc glibc-devel pcre pcre-devel openssl openssl-devel systemd-devel libtermcap-devel ncurses-devel libevent-devel readline-devel 
    elif [ $ID = "ubuntu" ];then
        apt update 
        apt -y install gcc make openssl libssl-dev libpcre3 libpcre3-dev zlib1g-dev  libreadline-dev libsystemd-dev 
    else
        color "不支持此操作系统!" 1
    fi
    [ $? -eq 0 ] ||  { color '安装软件包失败,退出!' 1; exit; }
}

install_lua () {
    tar xf ${LUA_FILE} -C ${SRC_DIR}
    LUA_DIR=${LUA_FILE%.tar*}
    cd ${SRC_DIR}/${LUA_DIR}
    make all test
}

install_haproxy(){
    cd ${CWD}
    tar xf ${HAPROXY_FILE} -C ${SRC_DIR}
    HAPROXY_DIR=${HAPROXY_FILE%.tar*}
    cd ${SRC_DIR}/${HAPROXY_DIR}
    make -j ${CPUS} ARCH=x86_64 TARGET=linux-glibc  USE_PROMEX=1 USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 USE_SYSTEMD=1 USE_CPU_AFFINITY=1 USE_LUA=1 LUA_INC=${SRC_DIR}/${LUA_DIR}/src/ LUA_LIB=${SRC_DIR}/${LUA_DIR}/src/ PREFIX=${HAPROXY_INSTALL_DIR}
    make install PREFIX=${HAPROXY_INSTALL_DIR}
    [ $? -eq 0 ] && color "HAPROXY编译安装成功" 0 ||  { color "HAPROXY编译安装失败,退出!" 1;exit; }
    [ -L /usr/sbin/haproxy ] || ln -s ${HAPROXY_INSTALL_DIR}/sbin/haproxy /usr/sbin/ 
    [ -d /etc/haproxy ] || mkdir /etc/haproxy 
    [ -d /var/lib/haproxy/ ] || mkdir -p /var/lib/haproxy/ 
    cat > /etc/haproxy/haproxy.cfg <<-EOF
global
maxconn 100000
stats socket /var/lib/haproxy/haproxy.sock mode 600 level admin
uid 99
gid 99
daemon

pidfile /var/lib/haproxy/haproxy.pid
log 127.0.0.1 local3 info

defaults
option http-keep-alive
option forwardfor
maxconn 100000
mode http
timeout connect 300000ms
timeout client 300000ms
timeout server 300000ms

listen stats
    mode http
    bind 0.0.0.0:9999
    stats enable
    log global
    stats uri /haproxy-status
    stats auth ${STATS_AUTH_USER}:${STATS_AUTH_PASSWORD}

#listen kubernetes-6443
#    bind ${VIP}:6443
#    mode tcp
#    log global
#    server ${MASTER1} ${MASTER1}:6443 check inter 3000 fall 2 rise 5
#    server ${MASTER2} ${MASTER2}:6443 check inter 3000 fall 2 rise 5
#    server ${MASTER3} ${MASTER2}:6443 check inter 3000 fall 2 rise 5

EOF
    
    groupadd -g 99 haproxy
    useradd -u 99 -g haproxy -d /var/lib/haproxy -M -r -s /sbin/nologin haproxy
}

start_haproxy () {
    cat > /lib/systemd/system/haproxy.service <<-EOF
[Unit]
Description=HAProxy Load Balancer
After=syslog.target network.target

[Service]
ExecStartPre=/usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q
ExecStart=/usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /var/lib/haproxy/haproxy.pid
ExecReload=/bin/kill -USR2 $MAINPID

[Install]
WantedBy=multi-user.target
EOF
    systemctl daemon-reload
    systemctl enable --now haproxy 
    systemctl is-active haproxy &> /dev/null && color 'HAPROXY安装完成!' 0 ||  { color 'HAPROXY 启动失败,退出!' 1; exit; }
    echo "-------------------------------------------------------------------"
    echo -e "请访问链接: \E[32;1mhttp://${LOCAL_IP}:9999/haproxy-status\E[0m"
    echo -e "用户和密码: \E[32;1m${STATS_AUTH_USER}/${STATS_AUTH_PASSWORD}\E[0m" 
}

check_file
install_packs
install_lua
install_haproxy
start_haproxy

自动生成证书脚本(v1.0)

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-09-27
#FileName:          crts.sh
#URL:               hhhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************

#/C=CN/ST=Beijing/L=Beijing/O=example/OU=Personal/CN=magedu.com
read -p "请输入(/C=CN/ST=Beijing/L=Beijing/O=example/OU=Personal/CN=shuhong.com):" args
read -p "请输入申请的域名(shuhong.com):" hn

cd /apps/harbor/certs 
openssl genrsa -out ca.key 4096

openssl req -x509 -new -nodes -sha512 -days 3650 -subj "$args"   -key ca.key -out ca.crt 

openssl genrsa -out $hn.key 4096

openssl req -sha512 -new  -subj "$args"  -key $hn.key  -out $hn.csr


cat > v3.ext <<-EOF
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names

[alt_names]
DNS.1=$hn
DNS.2=harbor.$hn
DNS.3=www.$hn
EOF

openssl x509 -req -sha512 -days 3650  -extfile v3.ext  -CA ca.crt -CAkey ca.key -CAcreateserial  -in $hn.csr  -out $hn.crt

自动安装DNS-bind(v1.0)

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-09-07
#FileName:          install-dns.sh
#URL:               hhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************

DOMAIN=shopxo.xo
HOST=www
HOST_IP=10.0.0.153
LOCALHOST=hostname -I | awk '{print $1}'

. /etc/os-release


color () {
    RES_COL=60
    MOVE_TO_COL="echo -en \\033[${RES_COL}G"
    SETCOLOR_SUCCESS="echo -en \\033[1;32m"
    SETCOLOR_FAILURE="echo -en \\033[1;31m"
    SETCOLOR_WARNING="echo -en \\033[1;33m"
    SETCOLOR_NORMAL="echo -en \E[0m"
    echo -n "$1" && $MOVE_TO_COL
    echo -n "["
    if [ $2 = "success" -o $2 = "0" ] ;then
        ${SETCOLOR_SUCCESS}
        echo -n $"  OK  "    
    elif [ $2 = "failure" -o $2 = "1"  ] ;then 
        ${SETCOLOR_FAILURE}
        echo -n $"FAILED"
    else
        ${SETCOLOR_WARNING}
        echo -n $"WARNING"
    fi
    ${SETCOLOR_NORMAL}
    echo -n "]"
    echo 
}


install_dns () {
    if [ $ID = 'centos' -o $ID = 'rocky' ];then
        yum install -y  bind bind-utils
    elif [ $ID = 'ubuntu' ];then
        apt update
        apt install -y bind9 bind9-utils bind9-host
    else
        color "不支持此操作系统,退出!" 1
        exit
    fi
    
}

config_dns () {
    if [ $ID = 'centos' -o $ID = 'rocky' ];then
        sed -i -e '/listen-on/s/127.0.0.1/localhost/' -e '/allow-query/s/localhost/any/' -e 's/dnssec-enable yes/dnssec-enable no/' -e 's/dnssec-validation yes/dnssec-validation no/'  /etc/named.conf
        cat >>  /etc/named.rfc1912.zones <<EOF
zone "$DOMAIN" IN {
    type master;
    file  "$DOMAIN.zone";
};
EOF
        cat > /var/named/$DOMAIN.zone <<EOF
\$TTL 1D
@   IN SOA  master admin (
                    1   ; serial
                    1D  ; refresh
                    1H  ; retry
                    1W  ; expire
                    3H )    ; minimum
            NS   master
master      A    ${LOCALHOST}         
$HOST       A    $HOST_IP
EOF
        chmod 640 /var/named/$DOMAIN.zone
        chgrp named /var/named/$DOMAIN.zone
    elif [ $ID = 'ubuntu' ];then
        sed -i 's/dnssec-validation auto/dnssec-validation no/' /etc/bind/named.conf.options
        cat >>  /etc/bind/named.conf.default-zones <<EOF
zone "$DOMAIN" IN {
    type master;
    file  "/etc/bind/$DOMAIN.zone";
};
EOF
        cat > /etc/bind/$DOMAIN.zone <<EOF
\$TTL 1D
@   IN SOA  master admin (
                    1   ; serial
                    1D  ; refresh
                    1H  ; retry
                    1W  ; expire
                    3H )    ; minimum
            NS   master
master      A    ${LOCALHOST}         
$HOST       A    $HOST_IP
EOF
        chgrp bind  /etc/bind/$DOMAIN.zone
    else
        color "不支持此操作系统,退出!" 1
        exit
    fi
    
    

}

start_service () {
    systemctl enable named
    systemctl restart named
    systemctl is-active named.service
    if [ $? -eq 0 ] ;then 
        color "DNS 服务安装成功!" 0  
    else 
        color "DNS 服务安装失败!" 1
        exit 1
    fi   
}

install_dns
config_dns
start_service

自动扫描网段,实现免密脚本(v1.0)

#!/bin/bash
#
#********************************************************************
#Author:            shuhong
#QQ:                985347841
#Date:              2022-09-05
#FileName:          ssh.sh
#URL:               hhhh
#Description:       The test script
#Copyright (C):     2022 All rights reserved
#********************************************************************
PASS=redhat
#设置网段最后的地址,4-255之间,越小扫描越快
END=254

IP=ip a s eth0 | awk -F'[ /]+' 'NR==3{print $3}'
NET=${IP%.*}.

. /etc/os-release

rm -f /root/.ssh/id_rsa
[ -e ./SCANIP.log ] && rm -f SCANIP.log

for((i=3;i<="$END";i++));do
    ping -c 1 -w 1  ${NET}$i &> /dev/null  && echo "${NET}$i" >> SCANIP.log &
done
wait

ssh-keygen -P "" -f /root/.ssh/id_rsa
if [ $ID = "centos" -o $ID = "rocky" ];then
    rpm -q sshpass || yum -y install sshpass
else
    dpkg -i sshpass &> /dev/null ||{ apt update; apt -y install sshpass; }
fi

sshpass -p $PASS ssh-copy-id -o StrictHostKeyChecking=no $IP 

AliveIP=(cat SCANIP.log)
for n in ${AliveIP[*]};do
    sshpass -p $PASS scp -o StrictHostKeyChecking=no -r /root/.ssh root@${n}:
done

#把.ssh/known_hosts拷贝到所有主机,使它们第一次互相访问时不需要输入回车
for n in ${AliveIP[*]};do
    scp /root/.ssh/known_hosts ${n}:.ssh/
done

安装openvpn脚本(v1.0)(目前适用rocky8)

#!/bin/bash
#
#*********************************************
#Author:           shuhong
#QQ:               985347841@qq.com
#Date:             2022-08-20
#FileName:         openvpn.sh
#URL:              www.hhhh.com
#Description:      The test script
#Copyright(C):     2022All right reserved
#*********************************************
#使用时注意修改iptables两行

. /etc/init.d/functions

Red="\e[1;31m"
Purple="\e[1;35m"
Green="\e[1;32m"
Blue="\e[1;36m"
Yellow="\e[1;33m"
End="\e[0m"

#检查登录用户
check_root(){
if [ $UID -ne 0 ]; then
    action "当前用户不是root,安装失败" false
    exit 1
fi
}

#检查yum源
check_yum(){
yum=$(yum repolist |grep -o epel &> /dev/null; echo $?)
if [  $yum -eq 0 ];then
    echo -e "$Green epel源存在$End"
else
    echo -e "$Yellow重新为你添加epel源$End"
    echo -en "
[epel]
name=EPEL
baseurl=https://mirror.tuna.tsinghua.edu.cn/epel/\$releasever/Everything/\$basearch
        https://mirrors.cloud.tencent.com/epel/\$releasever/Everything/\$basearch
        https://mirrors.huaweicloud.com/epel/\$releasever/Everything/\$basearch
        https://mirrors.aliyun.com/epel/\$releasever/Everything/\$basearch
gpgcheck=0
enabled=1 " > /etc/yum.repos.d/epel.repo 
    yum clean all
    yum makecache
    action "epel配置完成" true
fi
}

#安装openvpn
install_openvpn(){
if [ -e /etc/openvpn ];then
    action "openvpn已存在,安装失败" false
else 
    echo -e  "$Green开始安装openvpn$End"
    yum -y install openvpn
    action "安装openvpn" true
fi
}


#安装easy-rsa
install_easy_rsa(){
if [ -e /usr/share/easy-rsa/ ];then
    action "easy_rsa已存在" false
else
    echo -e "$Green开始安装easy-rsa$End"
    yum -y install easy-rsa
    action "安装easy-rasy" true 
fi
}

#展示软件版本
appinfo(){
    echo -e "$Yellow软件版本$End"
    yum list openvpn easy-rsa |tail -2|awk '{print $1,$2}'
}

check_apps(){
if [ -e /etc/openvpn -a -e /usr/share/easy-rsa/ ];then
    action "openvpn和easy-rsa已安装" true
else
    action "openvpn和easy-rsa未安装" false
    exit 1
fi
}

#检查Openvpen服务是否已经已启动
check_servivce(){
status=$(systemctl status openvpn@server.service |awk -F"[ ()]+" '/^ + Active/{print $4}')
if [ $status == "running" ];then
   echo -e "$Green服务正在运行$End"
   exit 0
fi
}

#生成CA证书和密钥
CA(){ 
    #echo CA   
    #准备好证书生成文件
    cp -r /usr/share/easy-rsa/3/ /etc/openvpn/easy-rsa 
    #准备证书颁发相关配置变量的文件
    cp /usr/share/doc/easy-rsa/vars.example  /etc/openvpn/easy-rsa/vars   
    #设置CA和服务器证书有效期
    echo -ne "set_var EASYRSA_CA_EXPIRE   36500\nset_var EASYRSA_CERT_EXPIRE 36500" >> /etc/openvpn/easy-rsa/vars
    #初始化PKI生成相关的文件和目录
    cd /etc/openvpn/easy-rsa/
    echo  -e "$Yellow生成PKI相关文件和目录$End"
    echo "yes"| /etc/openvpn/easy-rsa/easyrsa init-pki
    #创建 CA 机构证书环境
    echo -e "$Yellow生成CA证书和私钥$End"
    echo "CA" | /etc/openvpn/easy-rsa/easyrsa build-ca nopass         
    tree /etc/openvpn/easy-rsa/pki
}

server(){     
    cd /etc/openvpn/easy-rsa/
    echo -e "$Yellow生成证书申请文件和密钥文件$End"   
    echo -e "OpenVPN" | /etc/openvpn/easy-rsa/easyrsa gen-req server nopass
    echo -e "$Yellow生成服务器证书$End"
    echo "yes" | /etc/openvpn/easy-rsa/easyrsa sign server server
    echo -e "$Yellow生成Diffie-Hellma密钥$End"
    /etc/openvpn/easy-rsa/easyrsa gen-dh
    tree /etc/openvpn/easy-rsa/pki
}

startserver(){  
    cd /etc/openvpn/easy-rsa/ 
    #将CA和服务器证书相关文件复制到服务器相应的目录
    echo -e "$Yellow将CA和服务器证书相关文件复制到服务器相应的目录$End"
    cp /etc/openvpn/easy-rsa/pki/ca.crt  /etc/openvpn/server/
    cp /etc/openvpn/easy-rsa/pki/issued/server.crt  /etc/openvpn/server/
    cp /etc/openvpn/easy-rsa/pki/private/server.key  /etc/openvpn/server/
    cp /etc/openvpn/easy-rsa/pki/dh.pem  /etc/openvpn/server/
    ls -l /etc/openvpn/server/
    #准备启动的配置文件和日志目录 
    echo -e "$Yellow准备启动的配置文件和日志目录$End"
    cp /usr/share/doc/openvpn/sample/sample-config-files/server.conf  /etc/openvpn/
    echo -e "$Yellow生成ta.key$End"
    openvpn --genkey --secret /etc/openvpn/server/ta.key
    #准备账号密码认证脚本
    echo -e "$Yellow准备密码账户认证脚本$End"
    #mv /checkpsw.sh /etc/openvpn/checkpsw.sh   
    find / -name "checkpsw.sh"  -exec cp {} /etc/openvpn/ \; 
    chmod +x /etc/openvpn/checkpsw.sh 
    #提前生成吊销目录
    echo -e "$Yellow生成证书吊销文件$End"
    /etc/openvpn/easy-rsa/easyrsa gen-crl
    echo -ne "port 1194
proto tcp
dev tun
ca /etc/openvpn/server/ca.crt
cert /etc/openvpn/server/server.crt
key /etc/openvpn/server/server.key # This file should be kept secret
dh /etc/openvpn/server/dh.pem
server 10.8.0.0 255.255.255.0
push \"route 10.0.0.0 255.255.255.0\"
keepalive 10 120
cipher AES-256-CBC
compress lz4-v2
push \"compress lz4-v2\"
max-clients 2048
user openvpn
group openvpn
status /var/log/openvpn/openvpn-status.log
log-append /var/log/openvpn/openvpn.log
verb 3
mute 20
tls-auth /etc/openvpn/server/ta.key 0
crl-verify /etc/openvpn/easy-rsa/pki/crl.pem
script-security 3
auth-user-pass-verify /etc/openvpn/checkpsw.sh via-env
username-as-common-name" > /etc/openvpn/server.conf    
    getent passwd openvpn
    mkdir /var/log/openvpn
    chown openvpn:openvpn /var/log/openvpn
    ls -d -d /var/log/openvpn/
    find / -name "openvpn@.service"  -exec cp {} /usr/lib/systemd/system/ \;
    #cp /openvpn@.service /usr/lib/systemd/system/
    ll /usr/lib/systemd/system/ |grep openvpn
    systemctl daemon-reload 
    echo -e "$Yellow startOpen_VPN_service $End"
    systemctl enable --now openvpn@server
    systemctl status openvpn@server.service 
    echo "net.ipv4.ip_forward = 1" >>/etc/sysctl.conf
    sysctl -p
    iptables -t nat -A POSTROUTING -s 10.8.0.0/24 ! -d 10.8.0.0/24 -j SNAT --to-source 10.0.0.152  
    echo "iptables -t nat -A POSTROUTING -s 10.8.0.0/24 ! -d 10.8.0.0/24 -j SNAT --to-source 10.0.0.152" >> /etc/rc.d/rc.local
}

#检查证书是否申请过
check_crt(){
if [ -e etc/openvpn/client/$1 ];then
    echo -e "$Red证书已存在$End"
    exit
fi
}

#申请客户端证书
reqcrt(){
if [ -e /etc/openvpn/client/$1 ];then
    echo -e "$Red证书已存在$End"
    exit 1
else
    cd /etc/openvpn/easy-rsa/
    echo -e "$Yellow用户证书有效期默认设置150天$End"
    sed -ri "s/(^set_var EASYRSA_CERT_EXPIRE )[0-9]+$/\1150/i" /etc/openvpn/easy-rsa/vars
    echo -e "$Yellow生成客户端证书申请文件$End"
    mkdir /etc/openvpn/client/$1 
    echo "$1" | ./easyrsa gen-req $1 nopass
    echo "yes"| ./easyrsa sign client $1
    #find /etc/openvpn/easy-rsa/ \( -name "$1.key" -o -name "$1.crt" \) -exec cp {} /etc/openvpn/client/$1/ \;
    cp /etc/openvpn/easy-rsa/pki/private/$1.key /etc/openvpn/client/$1/client.key 
    cp /etc/openvpn/easy-rsa/pki/issued/$1.crt  /etc/openvpn/client/$1/client.crt
    cp /etc/openvpn/server/{ca.crt,ta.key} /etc/openvpn/client/$1
    #mv /etc/openvpn/client/$1/$1.key client.key
    #mv /etc/openvpn/client/$1/$1.key client.crt
    echo -ne "client
dev tun
proto tcp
remote $2 1194
resolv-retry infinite
nobind
#persist-key
#persist-tun
ca ca.crt
cert client.crt
key client.key
remote-cert-tls server
tls-auth ta.key 1
cipher AES-256-CBC
verb 3
compress lz4-v2
auth-user-pass
" > /etc/openvpn/client/$1/client.ovpn 
    zip /etc/openvpn/client/$1/$1.zip /etc/openvpn/client/$1/*
fi
}

#证书注销
crtdel(){
    cd /etc/openvpn/easy-rsa/
    echo "yes" | /etc/openvpn/easy-rsa/easyrsa revoke $1
    /etc/openvpn/easy-rsa/easyrsa gen-crl
    rm -rf /etc/openvpn/client/$1
}

#账号申请
useradd(){
   grep -o "$1" /etc/openvpn/psw-file && { echo -e "$Red用户已存在$End";exit 1; } ||  { echo -e "$1 $2" >> /etc/openvpn/psw-file;systemctl daemon-reload;systemctl restart openvpn@server.service;echo -e "$Green用户$1添加成功$End"; }
}

#账号删除
userdel(){
   grep -o "$1" /etc/openvpn/psw-file && { sed -ri "s/(^$1.*)//i"  /etc/openvpn/psw-file;echo -e "$Green删除$1用户成功$End";systemctl daemon-reload;systemctl restart openvpn@server.service; } ||  { echo -e "$Red用户$1不存在$End"; }
}

PS3="请按要求输入操作选项:"
select lists in 部署环境及安装软件 准备CA证书和服务器证书并启动服务 申请客户端证书 注销客户客户端证书 申请账号密码 删除用户名密码 退出;do
case $REPLY in
1)
    #部署环境及安装软件
    echo -e "$Blue$lists$End"
    check_root #检查是否是root用户登录
    check_servivce
    check_yum  #检查有没有eple源
    install_openvpn #安装openvpn
    install_easy_rsa #安装easy_rsa
    appinfo   #展示软件版本
    ;;
2)  
    #准备服务器证书并启动服务端
    echo -e "$Blue$lists$End"
    check_apps #检查是否安装软件包
    check_servivce  #检查Openvpen服务是否已经已启动
    CA  #生成CA证书和密钥
    server #生成server证书和密钥,准备server.conf文件
    startserver #启动openvpn服务
    ;;
3)  
    #申请客户客户端证书 
    echo -e "$Blue$lists$End"
    read -p "输入证书名称:" crtname
    read -p "输入vpn地址:"  ip
    check_crt $crtname 
    reqcrt $crtname $ip
    ;;
4)
    #注销客户客户端证书
    echo -e "$Blue$lists$End"
    ls -l /etc/openvpn/client/ |awk 'NR!=1{print $9}'
    read -p "请输入要删除的证书:" dcrtname
    crtdel $dcrtname
    ;;
5)  #申请账号密码
    echo -e "$Blue$lists$End"
    echo -e "$Yellow现有账号$End"
    awk '{print $1}' /etc/openvpn/psw-file
    read -p "请输入用户名(英文字母数字):" uname
    read -p "请输入密码(英文字母数字):" passd
    useradd $uname $passd
    ;;
6)
    #删除用户名密码
    echo -e "$Blue$lists$End"
    echo -e "$Yellow现有账号$End"
    awk '{print $1}' /etc/openvpn/psw-file
    read -p "请输入用户名(英文字母数字):" duname
    userdel $duname
    ;;
7)  #退出
    echo -e "$Blue$lists$End"
    exit
    ;;
*)
    echo "输入错误请重新输入"
    ;;
esac
done
#!/bin/sh
###########################################################
# checkpsw.sh (C) 2004 Mathias Sundman <mathias@openvpn.se>
#
# This script will authenticate OpenVPN users against
# a plain text file. The passfile should simply contain
# one row per user with the username first followed by
# one or more space(s) or tab(s) and then the password.

PASSFILE="/etc/openvpn/psw-file"
LOG_FILE="/var/log/openvpn-password.log"
TIME_STAMP=date "+%Y-%m-%d %T"

###########################################################

if [ ! -r "${PASSFILE}" ]; then
  echo "${TIME_STAMP}: Could not open password file \"${PASSFILE}\" for reading." >> ${LOG_FILE}
  exit 1
fi

CORRECT_PASSWORD=awk '!/^;/&&!/^#/&&$1=="'${username}'"{print $2;exit}' ${PASSFILE}

if [ "${CORRECT_PASSWORD}" = "" ]; then 
  echo "${TIME_STAMP}: User does not exist: username=\"${username}\", password=\"${password}\"." >> ${LOG_FILE}
  exit 1
fi

if [ "${password}" = "${CORRECT_PASSWORD}" ]; then 
  echo "${TIME_STAMP}: Successful authentication: username=\"${username}\"." >> ${LOG_FILE}
  exit 0
fi

echo "${TIME_STAMP}: Incorrect password: username=\"${username}\", password=\"${password}\"." >> ${LOG_FILE}
exit 1
openvpn@server.service
[Unit]
Description=OpenVPN Robust And Highly Flexible Tunneling Application On %I
After=network.target

[Service]
Type=notify
PrivateTmp=true
ExecStart=/usr/sbin/openvpn --cd /etc/openvpn/ --config %i.conf

[Install]
WantedBy=multi-user.target