Wake-on-LAN via Python?

Alex Martelli aleaxit at yahoo.com
Thu Aug 16 18:23:37 EDT 2001


"Gerhard Häring" <gerhard.nospam at bigfoot.de> wrote in message
news:s3gcl9.hm3.ln at gargamel.hqd-internal...
    ...
> Somebody who can read a bit of Perl cuold translate the Perl code to
Python,
> it's only a few lines.

Far more than 'a few' -- 215, though that includes docs & comments:-).

Assuming you can get all the docs & comments at original URL,

http://gsd.di.uminho.pt/jpo/software/wakeonlan/downloads/wakeonlan-0.40.tar.
gz

this should be a rough Python equivalent (sorry, can't test, no
wake-on-LAN PC around -- it will probably need fixes & tweaks):

#
# wake.py (main program)
#
import socket, getopt, sys, wakemod
VERSION = '0.40'
DEFAULT_IP = '255.255.255.255'
DEFAULT_PORT = socket.getservbyname('discard', 'udp')
#
# Process the command line
#
args, opts = getopt.getopt("hvp:i:f:")
fileis = None
for opt, val in opts:
    if opt=='-h': wakemod.usage(); sys.exit()
    elif opt=='-v': print "wakeonlan version",VERSION; sys.exit()
    elif opt=='-f': fileis = val
    elif opt=='-i': DEFAULT_IP = val
    elif opt=='-p': DEFAULT_PORT = val

if fileis is not None:
    wakemod.process_file(fileis, ('', DEFAULT_IP, DEFAULT_PORT))
elif not args: wakemod.usage(); sys.exit()

for arg in args:
    wakemod.wake(arg, DEFAULT_IP, DEFAULT_PORT)
#
# end of wake.py
#


#
# wakemod.py
#

import socket,re

# The 'magic packet' consists of 6 times 0xFF followed by 16 times
# the hardware address of the NIC. This sequence can be encapsulated
# in any kind of packet, in this case UDP to the discard port (9).
#
hwaddr_re = re.compile(':'.join(6*'[0-9A-Fa-f]{1,2}')+'$')
def wake(hwaddr, ipaddr, port):

    # check MAC address
    if not hwaddr_re.match(hwaddr):
        print "Invalid MAC address",hwaddr
        return

    # Generate magic sequence
    pkt = [chr(int(byte,16)) for byte in hwaddr.split(':')]
    pkt = chr(0xFF)*6 + ''.join(pkt*16)

    # Alocate socket and send packet
    raddr = socket.gethostbyname(ipaddr)
    proto = socket.getprotobyname('udp')
    them = raddr, proto
    S = socket.socket(socket.AF_INET,
        socket.SOCK_DGRAM, proto)
    S.setsockopt(socket.SOL_SOCKET,
        socket.SO_BROADCAST, 1)

    print "sending magic packet to %s:%s with %s"%(
        ipaddr, port, hwaddr)
    S.sendto(pkt, 0, them)

    S.close()

#
# process_file
#
igno_re = re.compile(r'\s*(#.*)?$')
def process_file(filename, defaults):
    for line in open(filename).readlines():
        # ignore comments & empty lines
        if igno_re.match(line): continue
        words = line[:-1].split()
        if len(words)<3:
            words.extend(defaults[len(words):])
        hwaddr, ipaddr, port = word[:3]
        if hwaddr: wake(hwaddr, ipaddr, port)

def usage():
    print "see original module..."


Alex






More information about the Python-list mailing list