Skip to content

Instantly share code, notes, and snippets.

@takumikinjo
Last active March 13, 2016 14:07
Show Gist options
  • Save takumikinjo/43d1972550ff6759a980 to your computer and use it in GitHub Desktop.
Save takumikinjo/43d1972550ff6759a980 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# Recieve WOL packet and then run vmrun command to boot VM.
#
# sudo ./wol-vmrun ~/path/to/vm1.vmx@xx:xx:xx:xx:xx:xx ~/path/to/vm2.vmx@yy:yy:yy:yy:yy:yy
#
# Tested on OS X El Capitan and VMware Fusion 8 Pro.
import re
import sys
import socket
import commands
from optparse import OptionParser
from struct import *
from contextlib import closing
WOL_PORT = 9
WOL_6FF_LEN = 6
MAC_ADDR_LEN = 6
VIX_VMRUN_PATH = '/Applications/VMware\ Fusion.app/Contents/Library/vmrun'
parser = OptionParser(
'Usage: %s [options] <vmx-path>@<mac> ...' % sys.argv[0]
)
(options, args) = parser.parse_args()
if len(args) < 1:
parser.print_help()
sys.exit(0)
def mac_vmx_pair(arg):
m = re.match(
r'^(.*)@([0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2})$',
arg,
re.IGNORECASE
)
if m and m.lastindex == 2:
vmx, mac = m.group(1), m.group(2)
return {
pack(
'6B',
*[int('0x' + b, 0) for b in mac.split(':')]
) : vmx
}
vmx_dict = reduce(
lambda d, e: dict(d, **e),
[mac_vmx_pair(arg) for arg in args]
)
if vmx_dict is None:
raise Exception('No valid couple of MAC and VMX exists')
sys.exit(1)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
with closing(sock):
sock.bind(('', WOL_PORT))
while True:
(buf, addr) = sock.recvfrom(1024)
if buf[0:WOL_6FF_LEN] == pack('6B', 0xff, 0xff, 0xff, 0xff, 0xff, 0xff):
buf = buf[WOL_6FF_LEN:]
mac = list(set([buf[
i * MAC_ADDR_LEN :
i * MAC_ADDR_LEN + MAC_ADDR_LEN
] for i in range(16)]))
print '%s has been recieved' % mac
if (len(mac) == 1):
vmx = vmx_dict[mac[0]]
if vmx:
cmd = VIX_VMRUN_PATH + ' -T fusion start' + ' "%s"' % vmx
print 'Run %s' % cmd
(status, stdout) = commands.getstatusoutput(cmd)
print 'Result ' + stdout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment