查看网络中多个服务器系统状态信息
- 监控各个节点的CPU、内存、磁盘。
依赖sshpass命令,所以需要先安装sshpass-1.06-1.el7.x86_64.rpm
- 授权
chmod +x check-host.sh
#!/bin/sh
#set -ex
#日志名称
LOG_FILE=host_check_$(date "+%Y%m%d").log
#注释变量或密码留空则执行脚本时输入
SSHPASS=[password]
if [[ ! -x $(command -v sshpass 2> /dev/null) ]]; then
echo -e 'sshpass does not exist, you should install sshpass.'
exit 0
fi
if [[ -z ${SSHPASS} ]]; then
read -s -p 'Enter SSH password for hosts:' SSHPASS
export SSHPASS
echo
else
export SSHPASS
fi
cat << EOF > ~/.ssh/config
StrictHostKeyChecking no
EOF
function format_output {
COL=$(($(tput cols) - 2))
IFS= read -r -d '\n' INPUT
MAX_LEN=$(echo "${INPUT}" | awk '{print length($0)}' | awk 'BEGIN {max = 0} {if ($1+0 > max+0) {max=$1; content=$0} } END {print content}')
if [[ ${MAX_LEN} -gt ${COL} ]]; then
MAX_LEN=${COL}
fi
MLINE=$(awk -v len=${MAX_LEN} 'BEGIN{OFS="─"; NF=len+1; print}')
echo "┌${MLINE}┐"
IFS=''
echo -n "${INPUT}" | while read LINE; do
if [[ -z ${LINE} ]]; then
echo "├${MLINE}┤"
else
printf "│%-${MAX_LEN}s│\n" "${LINE}"
fi
done
echo -e "└${MLINE}┘\n"
}
function ping_host {
ping -c 1 -W 1 $1 2>&1 > /dev/null || (echo -e "Host $1: Ping Failed.\n" && exit 1)
}
function get_host_status {
for HOST_IP in $(echo $1 | tr ',' ' '); do
(ping_host ${HOST_IP} && sshpass -e ssh root@${HOST_IP} 'bash -s' << EOF) | format_output | tee -a ${LOG_FILE}
export LANG=en_US.UTF-8
echo -e "Host: ${HOST_IP}\n"
echo -e "IP Address:"
ip a | grep global
echo -e "\nHost Route:"
ip route
echo -en "\nCheck Date: $(date)\nSystem Date: "
date
echo -e "\nSystem up time, Login user count, Load average:"
uptime
echo -e "\nMemory Status:"
free -m
echo -e "\nFile System Status:"
df -h | grep -v tmpfs
EOF
done
}
get_host_status 192.168.1.1,192.168.1.2,192.168.1.3
rm -f ~/.ssh/config