Tuesday, December 29, 2009

Wake on Lan in Python

I love Wake on Lan because it allows me to shutdown my little server at home, and still be able to remotely wake him up if necessary.

The well-known Depicus WoL pages provide Windows binaries (GUI and CLI) to send WoL packets, as well as an online form.

If you are on Linux or prefer sending it on your own (I mean, not using a closed binary), you can use a few lines of Python as explained by myf00 with Python3 code.

The following code is the same for Python2 (just removed b prefix in front of binary strings).
#!/usr/bin/python
from socket import socket, AF_INET, SOCK_DGRAM, SOL_SOCKET, SO_BROADCAST

data = '\xFF\xFF\xFF\xFF\xFF\xFF' + '\xAA\xAA\xAA\xAA\xAA\xAA' * 16

sock = socket(AF_INET, SOCK_DGRAM)
sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
sock.sendto(data, ('<broadcast>', 9))
sock.close()
Replace AA's in \xAA\xAA\xAA\xAA\xAA\xAA with your MAC address.
If you're on LAN, should work as is. If you're on the internet, replace <broadcast> with your public IP address (you may need to enable a "WoL proxy" feature, or manually configure your router to forward UDP port 9 packets to your server).

3 comments:

  1. Mine is python3 and it shows this error

    line 8, in
    sock.sendto(data, ('', 9))
    TypeError: sendto() takes exactly 3 arguments (2 given)

    Google the error and it seems to have something todo with encoding.
    Do you know how to fix it.
    THank a lot for the code.

    ReplyDelete
  2. You're welcome :)

    As I said the code is for Python2, for Python3 just see the original author http://myf00.net/?p=215
    In addition, you have to set something in the sendto(). If the remote computer address is A.B.C.D then use:
    sock.sendto(data, ('A.B.C.D', 9))

    Also, most distributions have a wakeonlan package (see Debian http://packages.debian.org/search?keywords=wakeonlan), it may be more convenient: wakeonlan -i A.B.C.D -p 9 00:11:22:33:44:55

    ReplyDelete
  3. Nice article and so impressive.
    thanks for sharing

    ReplyDelete