Wake-on-lan to trigger virtual-machine with kvm and libvirt

I'm doing virtualization with KVM and managing it via the Libvirt daemon.

How do I configure Libvirt or KVM to listen for Wake-On-Lan packets sent the the Virtual Machine's NIC's MAC address and to start the Virtual Machine when such a packet is received?


Solution 1:

I've found Libvirt-wakeonlan which seems to do it. I have no idea how mature it is and how well it works. The approach seems right. https://github.com/simoncadman/libvirt-wakeonlan

Solution 2:

you can use my script which essentialy does the same as libvirt-wakeonlan, I made it because I could not get libvirt-wakeonlan to work... this is just a simple script which you can put in a startup script and have it running on boot.

It listens to udp port 9 (port 7 is also used sometimes afaik but guacamole - the remote vnc/rdp I use - sends at port 9) and checks the MAC adress when it sees a magic packet. If there is a vm in virsh with this MAC adress it will wake the machine up.

https://gitlab.com/-/snippets/2183494

#!/bin/bash

nc -dknl -p 9 -u | # listen to udp port 9 for packets, check if it is a magic packet
 stdbuf -o0 xxd -c 6 -p |
 stdbuf -o0 uniq |
 stdbuf -o0 grep -v 'ffffffffffff' |
 while read ; do
    mac="${REPLY:0:2}:${REPLY:2:2}:${REPLY:4:2}:${REPLY:6:2}:${REPLY:8:2}:${REPLY:10:2}"
    # parse mac found in magic packet
    for i in $(virsh list --all --name); do # loop through libvirt machines
        vmmac=$(virsh dumpxml $i | grep "mac address" | awk -F\' '{ print $2}') # get each machines MAC
        if [ $vmmac = $mac ]; then # compare MACs, if match do;
            echo $mac;
            echo $i;
            virsh start $i
            virsh resume $i
        fi
    done
done