wol/wol.py
2011-03-05 08:46:43 -05:00

78 lines
2.1 KiB
Python
Executable File

#!/usr/bin/env python
import re
import cgi
from subprocess import *
# Enable these for debugging
import cgitb
cgitb.enable()
MAC_FILE = '/etc/wol.macs'
REFRESH = 15
def header():
print "Content-Type: text/html\n"
def printHead(title):
print '''<head>
<title>%s</title>
<meta http-equiv="refresh" content="%s">
</head>''' % (title, REFRESH)
def checkup(hostname):
p = Popen(['ping', '-c1', '-W2', hostname], stdout = PIPE, stderr = PIPE)
for line in p.communicate()[0].split('\n'):
if re.search(r'\sbytes\sfrom\s', line):
return True
return False
def getMACs():
f = open(MAC_FILE, 'r')
macs = {}
for line in f.read().split('\n'):
m = re.match('(\S+)\s+(\S+)', line)
if m is not None:
name, mac = m.group(1, 2)
macs[name] = mac
return macs
def main():
header()
print '<html>'
printHead('Wake on LAN Interface')
print '<body>'
print '<h2>%s</h2>' % 'Wake on LAN Interface'
macs = getMACs()
form = cgi.FieldStorage()
if 'name' in form:
name = form['name'].value
if name in macs:
if 'wake' in form:
Popen(['wakeonlan', macs[name]], stdout = PIPE, stderr = PIPE)
elif 'shutdown' in form:
Popen(['ssh', '-i', '/var/www/.ssh/id_rsa',
'-l', 'root', name, 'shutdown', '-h', 'now'],
stdout = PIPE, stderr = PIPE)
print '<ul>'
names = macs.keys()
names.sort()
for name in names:
up = checkup(name)
print '<li>'
print '<form method="post">'
print '<span style="color: %s;">' % ('#0C0' if up else '#C00')
print name
print '</span> &nbsp; '
print '<input type="hidden" name="name" value="%s"/>' % name
print '<input type="submit" name="wake" value="Wake" />'
print ' &nbsp; ';
print '<input type="submit" name="shutdown" value="Shutdown" />'
print '</form>'
print '</li>'
print '</ul>'
print '</body></html>'
if __name__ == "__main__":
main()