【轉(zhuǎn)】PVE 虛擬機(jī)心跳檢測(cè)并重啟
本文地址:blog.lucien.ink/archives/531
不知為何,PVE 中的 OpenWrt 時(shí)不時(shí)會(huì)宕機(jī),這是背景。秉承著能用就行的思想,寫(xiě)了一個(gè)腳本,每隔一分鐘檢測(cè)一次虛擬機(jī)是否有心跳,如果沒(méi)有心跳,就強(qiáng)制重啟虛擬機(jī),記錄在這里。
#!/usr/bin/env bash
function check_and_restart() {
? ? vm_id="${1}"
? ? vm_ip="${2}"
? ? # curl --connect-timeout 5 -sSL "${vm_ip}" > /dev/null
? ? ping -c 1 "${vm_ip}" > /dev/null
? ? if [[ $? != 0 ]]; then
? ? ? ? now=`timedatectl status | grep 'Local time' | awk -F"Local time: " '{ print $2 }'`
? ? ? ? echo "[${now}] [NO] id = ${vm_id}, ip = ${vm_ip}"
? ? ? ? /usr/sbin/qm stop "${vm_id}"
? ? ? ? /usr/sbin/qm start "${vm_id}"
? ? fi
}
function main() {
? ? vm_list=${1}
? ? for each in ${vm_list}; do
? ? ? ? vm_id=`echo "${each}" | awk -F: '{ print $1 }'`
? ? ? ? vm_ip=`echo "${each}" | awk -F: '{ print $2 }'`
? ? ? ? check_and_restart "${vm_id}" "${vm_ip}"
? ? done
}
# 需要檢查的虛擬機(jī)列表,格式為 vm_id:vm_ip
vm_list="
100:192.168.1.100
101:192.168.1.101
102:192.168.1.102
"
# 打印時(shí)間
# timedatectl status | grep 'Local time' | awk -F"Local time: " '{ print $2 }'
main "${vm_list}"
以我自己為例,將以上文件保存至?/root/check_and_restart/check_and_restart.sh
,然后在?crontab
?里寫(xiě)入:
*/1 * * * * bash /root/check_and_restart/check_and_restart.sh >> /root/check_and_restart/log.txt
隨后執(zhí)行?systemctl restart cron
?即可。