summaryrefslogblamecommitdiffstats
path: root/gearman/wolWorker.py
blob: f853b58e3b185e31013fe47abdba1a12bec07955 (plain) (tree)



































                                                                        
                               


                                     
             
#!/usr/bin/python

from gearman import GearmanWorker
import socket
import struct

# http://code.activestate.com/recipes/358449-wake-on-lan/
def wake_on_lan(macaddress):
    """ Switches on remote computers using WOL. """

    # Check macaddress format and try to compensate.
    if len(macaddress) == 12:
        pass
    elif len(macaddress) == 12 + 5:
        sep = macaddress[2]
        macaddress = macaddress.replace(sep, '')
    else:
        raise ValueError('Incorrect MAC address format')
 
    # Pad the synchronization stream.
    data = ''.join(['FFFFFFFFFFFF', macaddress * 20])
    send_data = '' 

    # Split up the hex values and pack.
    for i in range(0, len(data), 2):
        send_data = ''.join([send_data,
                             struct.pack('B', int(data[i: i + 2], 16))])

    # Broadcast it to the LAN.
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    sock.sendto(send_data, ('<broadcast>', 7))

def wolTask(worker, job):
    wake_on_lan(job.data)
    print 'WOL send to: %s' % job.data
    return 'Magic packet send.'

worker = GearmanWorker(["127.0.0.1"])
worker.register_task('wol', wolTask)
worker.work()