Skip to content

Instantly share code, notes, and snippets.

@Westacular
Created November 11, 2012 23:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Westacular/4056779 to your computer and use it in GitHub Desktop.
Save Westacular/4056779 to your computer and use it in GitHub Desktop.
Sends a wake-on-lan magic packet for the given MAC address to either the broadcast address of the local subnet, or, if provided, some other hostname. An alternate port can also be optionally provided.
# WakeOnLan
#
# Sends a wake-on-lan magic packet for the given MAC address
# to either the broadcast address of the local subnet, or,
# if provided, some other hostname.
# An alternate port can also be optionally provided.
import struct, socket
import sys
def wake(mac_address, hostname=None, port=9):
# Convert the MAC address to a packed binary form
addr_bytes = ''.join(chr(int(byte, 16)) for byte in mac_address.split(':'))
# Construct the WOL "magic packet"...
payload = b'\xFF' * 6 + addr_bytes * 16
if not hostname:
# If no hostname is specified, broadcast as a UDP packet on the local subnet
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto(payload, ('<broadcast>', port))
print 'Magic packet for ' + mac_address + \
' has been sent to broadcast address with port ' + str(port)
finally:
s.close()
else:
# If a hostname is specified, resolve it, etc, and send the UDP packet
try:
records = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_DGRAM)
except socket.gaierror as e:
print '\nCould not resolve host "' + hostname + '": ' + e[1]
sys.exit(1)
for res in records:
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error as msg:
s = None
continue
try:
s.connect(sa)
except socket.error as msg:
s.close()
s = None
continue
break
if s is None:
print '\nCould not open socket'
sys.exit(1)
s.send(payload)
print 'Magic packet for ' + mac_address + \
' has been sent to ' + sa[0] + \
' port ' + str(port)
s.close()
if __name__ == '__main__':
# Example uses
wake('aa:bb:cc:dd:ee:ff', 'myhost.example.org')
wake('aa:bb:cc:dd:ee:ff')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment