Files
ansible/roles/proxmox/files/check_proxmox_vm.sh
2025-04-06 18:04:33 +02:00

84 lines
1.8 KiB
Bash
Executable File

#!/bin/bash
# Configuration
VM_ID=303
TARGET_IP="192.168.20.36" # Replace with the IP of your VM
PORT=22
CHECK_INTERVAL=300 # 5 minutes in seconds
LOG_FILE="/var/log/vm_monitor.log"
# Function to log messages
log_message() {
echo "$(date): $1" | tee -a $LOG_FILE
}
# Check if running on a Proxmox host
if ! command -v qm &>/dev/null; then
log_message "qm command not found. This script must run on a Proxmox host."
exit 1
fi
# Function to check port
check_port() {
# Try nc first if available
if command -v nc &>/dev/null; then
if nc -z -w 5 $TARGET_IP $PORT 2>/dev/null; then
return 0 # Port is open
else
return 1 # Port is closed
fi
# Fall back to nmap if nc is not available
elif command -v nmap &>/dev/null; then
if nmap -p $PORT $TARGET_IP | grep -q "$PORT/tcp.*open"; then
return 0 # Port is open
else
return 1 # Port is closed
fi
else
log_message "Neither nc nor nmap found. Please install one of them."
exit 1
fi
}
# Function to restart the VM
restart_vm() {
log_message "Port $PORT is not reachable. Restarting VM $VM_ID..."
# Stop the VM
qm stop $VM_ID
if [ $? -ne 0 ]; then
log_message "Failed to stop VM $VM_ID. Trying force stop..."
qm stop $VM_ID --force
fi
# Wait for VM to fully stop
log_message "Waiting for VM to stop..."
sleep 10
# Start the VM
qm start $VM_ID
if [ $? -ne 0 ]; then
log_message "Failed to start VM $VM_ID. Manual intervention required."
exit 1
fi
log_message "VM $VM_ID has been restarted."
}
# Main loop
log_message "Starting monitoring of VM $VM_ID on port $PORT..."
log_message "Press Ctrl+C to exit."
while true; do
# Check if port 22 is open
if ! check_port; then
restart_vm
else
log_message "Port $PORT is reachable. VM is running normally."
fi
# Wait for the next check
log_message "Sleeping for $CHECK_INTERVAL seconds..."
sleep $CHECK_INTERVAL
done