#!/bin/bash
# Function to display usage information
usage() {
echo "Usage: $0 <IP_address> | <MAC_address>"
echo " <IP_address> - IPv4 address of the VM"
echo " <MAC_address> - MAC address of the VM (e.g., 00:1A:2B:3C:4D:5E)"
exit 1
}
# Check if any arguments are provided
if [[ -z "$1" ]]; then
echo "Error: Missing argument."
usage
fi
# Check if the argument is an IPv4 address
if [[ "$1" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
IP="$1"
echo -n "Looking for VM with IP $IP... "
# Ping the IP to check if it's reachable and valid
ping -c1 "$IP" > /dev/null 2>&1
if [[ "$?" -ne 0 ]]; then
echo "Error: IP address is not reachable or valid."
exit 1
fi
# Find the MAC address from the ARP table
MAC=$(arp -n | grep -E "^$IP[^0-9]" | awk '{print $3}')
if [[ -z "$MAC" ]]; then
echo "Error: MAC address not found for IP $IP."
exit 1
fi
echo "Found MAC: $MAC"
# Check if the argument is a MAC address
elif [[ "$1" =~ ^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$ ]]; then
MAC="$1"
echo "Using provided MAC address: $MAC"
else
echo "Error: Invalid input. Please provide a valid IPv4 or MAC address."
usage
fi
echo "---"
echo "Found VMs:"
# Find VMs by MAC address
VMS=$(grep -i "$MAC" -R /etc/pve/ | grep -oE "/[0-9]+\.conf" | grep -oE "[0-9]+" | sort -u)
if [[ -z "$VMS" ]]; then
echo "Error: No VMs found for MAC address $MAC."
exit 1
fi
echo "$VMS"