用ChatGPT写脚本-PVE虚拟机监控重启

之前入了N5105+PVE的坑,跑iKuai老是挂掉,其它的VM倒是很稳定.试着更新到5.19内核和最新的CPU微码还是不能解决.PVE还装了一堆别的VM懒得切换到ESXi了,只能暂时跑个脚本来监控虚拟机状态,挂掉就重启它.把需求告诉ChatGPT,马上就给出想要的脚本内容,稍微调整一下就可以使用了.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/bin/bash

# Set vmid and target IP
vmid=101
target=192.168.1.1

# Set ping timeout to 3 seconds
timeout=3

# Set maximum number of pings to 2
max_pings=2

# Set the interval between pings to 15 seconds
interval=15

while true; do
# Set counter to 0
counter=0

# Loop until the counter exceeds the max pings
while [ $counter -lt $max_pings ]; do
# Ping the target and increment the counter
if ! ping -c 1 -W $timeout $target &> /dev/null; then
((counter++))
else
# Reset the counter if the ping is successful
counter=0
fi

# Sleep for the interval before pinging again
sleep $interval
done

# If the loop finishes, that means that ping failed max_pings times
# in a row, so we can check for the lock file and restart the virtual machine
if [ -f "/var/lock/qemu-server/lock-${vmid}.conf" ]; then
rm "/var/lock/qemu-server/lock-${vmid}.conf"
fi
qm stop $vmid
sleep 15
qm start $vmid
sleep 60

# Record the restart time in the log file
echo "Virtual machine restarted at $(date)" >> /var/log/vmrestart.log
done