生产实践:
通过vip查询lvs平台接口获取后端rip
学习技巧:
curl、dig、jq、shell数组等使用(curl实用技巧)
脚本内容:
#!/bin/bash
##############################################################################
# $Name: clvs.sh
# $Version: v1.0
# $Function: Through the domain name lookup VIP,rip,site and so on...
# $Author: Zhihe An
# $Copyright (c) https://chegva.com
# $Create Date: 2018-09-13
##############################################################################
#通过域名解析出vip
ip=`dig +short $1 |egrep -v "cname|srv|xx"|sort`
#简单的输入判断,然后进入for循环
[[ -n "$1" ]] && {
for i in $ip
do
#打印50个#号
printf "%0.s#" {1..50}
#输出vip
echo -e "\nvip: ${i}"
#curl请求lvs平台查询接口,过滤出对应的rip信息,由于vip<-->rip是多对多的关系返回的是模糊查询,这里必须过滤
rip=($(curl -X GET --header 'Accept: application/json' "http:/chegva.com/vx/lvs/search/vs?search=${i}" 2>/dev/null | sed '/href/d' | python -m json.tool | ack -w -C 5 "${i}" |egrep 'site|rips' |sort -n |uniq))
#输出机房
echo -e "site: $(echo ${rip[@]: -1} | sed -e 's/^["]*//g' -e 's/[",]*$//g')"
#过滤出rip的IPv4地址,并解析出主机名
echo "rip:"
echo ${rip[@]} | grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" |sort -n |uniq |xargs -n1 hostconv
echo
sleep 2
done
} || {
echo 'WARN: Empty argument!'
exit
}
#由于lvs接口vip是模糊查询,返回的json数据乱了,放弃!
# host=($(curl -X GET --header 'Accept: application/json' "http:/chegva.com/vx/lvs/search/vs?search=${i}" 2>/dev/null | sed '/href/d' |python -m json.tool | jq -r '.[].rips,.[].site'|uniq))
# index=$((${#host[@]}-1))
# echo "site:${host[${#host[*]}-1]}"
# echo -e "site: ${host[@]: -1}"
# unset host[$index]
# echo "${host[@]}" | grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" |sort -n |uniq |xargs -n1 hostconv
# curl -X GET --header 'Accept: application/json' "http:/chegva.com/vx/lvs/search/vs?search=${i}" 2>/dev/null | sed '/href/d' | python -m json.tool | ack -w -C 5 "${i}" |egrep 'site|rips' |sort |uniq |grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" |sort -n |uniq |xargs -n1 hostconv
#返回的数据根据查询vip过滤后,再构建成json格式取出来,有点绕远啦,弃用!
# curl -X GET --header 'Accept: application/json' 'http:/chegva.com/vx/lvs/search/vs?search=${i}' 2>/dev/null | sed '/href/d' |python -m json.tool |ack -w -C 5 "${i}" |egrep 'site|rips' |sort |uniq |sed -e '/site/s/,//g' -e '1i\{' -e '$a\}' |jq -r '.rips,.site'
◎查看效果