因为要统计K8S的pod的limits和request以及实际使用率与分配的总和所以写了这个脚本,直接输入对应的命名空间就能使用
# !/bin/bash
echo '这是现有的命名空间请选择'
/usr/local/bin/kubectl get ns
echo '----------------------------------------------------------'
read -p '输入你要查询的命名空间:' name
echo "您选定该命名空间:$name 正在查询请稍后"
/usr/local/bin/kubectl get pod -n $name | sed -n '2,$p' | awk -F ' ' '{print $1}' > /tmp/name.txt
number=$(cat /tmp/name.txt | wc -l)
pod(){
for (( i=1;i<=$number;i++ ))
do
line=$(cat /tmp/name.txt | sed -n ''$i'p' )
if [[ $i == 1 ]]
then
echo "pod名称,limits(cpu/memory),requests(cpu/memory),top(cpu/memory)" > ./end.csv
f=$( /usr/local/bin/kubectl describe pod $line -n $name | grep -A 2 Limits |sed -n '2,$p' | awk -F ' ' '{printf $2"/"}' | awk -F '/' '{print $1"/"$2}' )
e=$( /usr/local/bin/kubectl describe pod $line -n $name | grep -A 2 Requests |sed -n '2,$p' | awk -F ' ' '{printf $2"/"}' | awk -F '/' '{print $1"/"$2}' )
r=$(/usr/local/bin/kubectl top pod $line -n $name | sed -n '2,$p' | awk -F ' ' '{print $2"/"$3}')
echo "$line,$f,$e,$r" >> ./end.csv
else
f=$( /usr/local/bin/kubectl describe pod $line -n $name | grep -A 2 Limits |sed -n '2,$p' | awk -F ' ' '{printf $2"/"}' | awk -F '/' '{print $1"/"$2}' )
e=$( /usr/local/bin/kubectl describe pod $line -n $name | grep -A 2 Requests |sed -n '2,$p' | awk -F ' ' '{printf $2"/"}' | awk -F '/' '{print $1"/"$2}' )
echo "$line,$f,$e,$r" >> ./end.csv
fi
#cat end.csv | awk -F ':' '{print $2}' | awk -F ',' '{print $1}' | sed -n '2,$p' > /tmp/te.txt
done
}
limits-statistics(){
cat ./end.csv | awk -F ',' '{print $2}' | awk -F ',' '{print $1}' | sed -n '2,$p' > /tmp/te.txt
filename="/tmp/te.txt"
# 使用awk计算总和
awk -F '/' '{
split($1, a, /[mMi]/);
split($2, b, /[mMi]/);
sum1 += a[1]; sum2 += b[1];
}
END {
printf sum1
printf "/"
printf sum2
}' "$filename" > /tmp/5.txt
p=$(cat /tmp/5.txt)
echo "limits-all: $p" >> ./end.csv
}
requests-statistics(){
cat ./end.csv | awk -F ',' '{print $2}' | awk -F ',' '{print $1}' | sed -n '2,$p' > /tmp/te.txt
filename="/tmp/te.txt"
# 使用awk计算总和
awk -F '/' '{
split($1, a, /[mMi]/);
split($2, b, /[mMi]/);
sum1 += a[1]; sum2 += b[1];
}
END {
printf sum1
printf "/"
printf sum2
}' "$filename" > /tmp/5.txt
o=$(cat /tmp/5.txt)
echo "requests-all: $o" >> ./end.csv
}
echo "---------------------------------------------------"
echo "查询完毕,已在当前目录生成end.csv文件,请使用cat end.csv查看"
pod
limits-statistics
requests-statistics
会生成end.csv格式的文件直接lrzsz命令下载下来查看即可