76 lines
1.6 KiB
Bash
Executable File
76 lines
1.6 KiB
Bash
Executable File
#!/bin/bash
|
|
|
|
# Configuration
|
|
VM_ID=$1
|
|
TARGET_IP=$2
|
|
PORT=22
|
|
LOG_FILE="/var/log/vm_monitor_${VM_ID}.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 execution
|
|
log_message "Starting monitoring of VM $VM_ID on port $PORT..."
|
|
|
|
# Check if port 22 is open
|
|
if ! check_port; then
|
|
restart_vm
|
|
else
|
|
log_message "Port $PORT is reachable. VM is running normally."
|
|
fi
|