Python

Using Wake-on-LAN with Python

Most modern PCs and Macintoshes feature Wake-on-LAN. This feature, originally called “Magic packet” (PDF) by AMD, allows you to start a PC remotely by sending a specially formed “magic packet” to its Ethernet interface. On Macs running OS X, Wake-on-LAN seems to work only when the Mac is in sleep mode, not when it is completely turned off. The original intent was to allow administrators to boot PCs remotely to run backups, but with the spread of DSL, there are other uses.

For instance, I have a low-noise Solaris machine running 24/7 at my home (angband.majid.fm), and when I need to access my (noisy) home PC, I just log on to that machine via SSH, wake up the PC and then log on remotely using pcAnywhere. The same works with my iMac G4

Here is a very simple Python script that starts a machine with a given MAC address:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto('\xff'*6 + '\x00\x02\xb3\x07\xb6\xd1'*16, ('192.168.1.255', 80))

It will start the machine with MAC address 00:02:B3:07:B6:D1 on the subnet 192.168.1/24 by sending a Wake-on-LAN magic packet to the subnet-directed broadcast IP address.

Update (2003-12-05):

Now that you have woken your Mac, how do you send it back to sleep? Read this article to find out.

Update (2006-03-19):

On certain versions of Linux, you may get a “permission denied” error message because you are trying to send a packet to a broadcast address. The following code should work:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto('\xff'*6 + '\x00\x02\xb3\x07\xb6\xd1'*16, ('192.168.1.255', 80))

Python used to defend human rights

Patrick Ball is the author of a book called Making the Case describing how information technology and notably databases of human rights abuse reports can yield statistical evidence of wrongdoing by specific individuals (say, policemen).

He testified at Slobodan Milosevic’s trial in The Hague. Apparently, the processing was done in Python, see page 2 of this Wired article for more details.