Skip to content

Instantly share code, notes, and snippets.

@regen100
Created May 23, 2014 15:30
Show Gist options
  • Save regen100/a615ce9577f21a1d90c5 to your computer and use it in GitHub Desktop.
Save regen100/a615ce9577f21a1d90c5 to your computer and use it in GitHub Desktop.
Suspend on LAN Service
import win32serviceutil
import servicemanager
import ctypes
import socket
import select
import netifaces
import time
from contextlib import closing
def suspend(hibernate=False):
ctypes.windll.PowrProf.SetSuspendState(hibernate, 0, 0)
def macaddrs():
return [netifaces.ifaddresses(iface_name)[netifaces.AF_LINK][0]['addr'].lower() for iface_name in netifaces.interfaces()]
def get_macaddr(data):
if data[:6] != '\xFF' * 6 or len(data) != 102:
return None
mac = data[6:12]
if data[6:] != mac * 16:
return None
return ':'.join(['%02x' % ord(x) for x in mac])
class SoLService(win32serviceutil.ServiceFramework):
_svc_name_ = 'SoLService'
_svc_display_name_ = 'Suspend on LAN'
_svc_description_ = 'Suspend on LAN Service'
port = 9
hibernate = True
def SvcStop(self):
self.run = False
def SvcDoRun(self):
self.run = True
with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as sock:
sock.bind(('', self.port))
while self.run:
rlist, wlist, xlist = select.select([sock], [], [], 0)
for s in rlist:
try:
data, addr = s.recvfrom(1024)
if get_macaddr(data) in macaddrs():
servicemanager.LogInfoMsg('Suspended by SoL')
suspend(self.hibernate)
except socket.error as e:
pass
else:
time.sleep(0.1)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(SoLService)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment