返回顶部

upstream的IP池地址更换

upstream的IP池地址更换

使用场景,根据访问URL链接的返回告警,进行更换nginx负载均衡地址,实现地址池IP的更换和剩余IP监测

#!/bin/bash
#********************************************************************
#Author:        wei
#********************************************************************
read -p '请输入城市【如,beijing】:' City
List=$(cat list)
Get_config=$(cd /usr/local/openresty/nginx/confs && ls ${City}.conf})echo ${Get_config} ${List} &> /dev/null
Check_iplist () {
Old_IP=$(sed -nr "/#upstream start/,/#upstream end/p" ${Get_config}  |grep server   |awk -F'[ ]+|:' '{print $3}' |sort-nr |uniq |wc -l)
New_IP=$(cat list|wc -l)
if [ ${Old_IP} -eq ${New_IP} ];then
    echo -e '\033[1;5;33m Waring!!! 请添加替换IP地址\033[0m'
elif [ ${Old_IP} -le ${New_IP} ];then
    echo -e '\033[1;5;32m  IP列表有剩余,放心使用 \033[0m'
else
    echo -e '\033[1;5;32m IP 列表已使用完毕请添加后在执行脚本\033[0m' && exit
fi
}

Replace_IP () {
Port_service=$(sed -nr "/#upstream start/,/#upstream end/p" ${Get_config} |grep -v  "#" |grep server |awk -F":|[ ]+|;"'{print $4}' )
echo ${Port_service}
for i in ${Port_service};do
    Old_IP=$(sed -nr "/#upstream start/,/#upstream end/p" ${Get_config} | egrep ${i} |grep server   |awk -F'[ ]+|:' '{print $3}' |sort -nr |uniq )
    echo ${Old_IP} > tmp-ip
    New_IP=$(echo ${Old_IP} ${List} |tr ' ' '\n' |sort -nr |uniq -u|head -1 )
    echo ${New_IP}  &> /dev/null
    Sed_IP=$(sed -nr '/#upstream start/,/#upstream end/p' ${Get_config} |grep ${i} |egrep  -v '#|upstream' |awk -F'[ ]+|:' '{print $3}' |head -1)
    sed -ri.bak "s/server  ${Sed_IP}:${i};/#server  ${Sed_IP}:${i};/" ${Get_config}
    sed -ri "/server  ${Sed_IP}:${i};/a\        server  ${New_IP}:${i};" ${Get_config}
done
}


load_nginx () {
nginx -t && nginx -s reload && echo -e '\033[32m 配置成功\033[0m' || echo -e '\033[31m 语法错误请检查配置\033[0m'
}

Check_iplist
Replace_IP
load_nginx

 

 

 

posted @ 2022-08-10 18:09  九尾cat  阅读(153)  评论(0编辑  收藏  举报