• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python
2#pylint: disable-msg=C0111
3import BeautifulSoup,optparse
4
5try:
6    import pycurl
7except ImportError:
8    print "Failed to import pycurl. Ignoring."
9
10###############################################################
11# Digital Loggers Web Power Switch management
12###############################################################
13# Version: 0.01
14# Description: This is both a module and a script
15#
16#              The module provides a python class named
17#              DLIPower that allows managing the web power
18#              switch from python programs.
19#
20#              When run as a script this acts as a command
21#              line utilty to manage the DLI Power switch.
22# Author: Dwight Hubbard d@dhub.me
23# Copyright: This module may be used for any use personal
24#            or commercial as long as the author and copyright
25#            notice are included in full.
26###############################################################
27
28# Global settings
29# Timeout in seconds
30TIMEOUT=5
31
32class powerswitch:
33    """ Manage the DLI Web power switch """
34    def __init__(self,userid='admin',password='4321',hostname='192.168.0.100'):
35        self.userid=userid
36        self.password=password
37        self.hostname=hostname
38        self.contents=''
39    def verify(self):
40        """ Verify we can reach the switch, returns true if ok """
41        return self.geturl()
42    def body_callback(self,buf):
43        self.contents=self.contents+buf
44    def geturl(self,url='index.htm') :
45        self.contents=''
46        curl = pycurl.Curl()
47        curl.setopt(curl.TIMEOUT,TIMEOUT)
48        curl.setopt(curl.URL, 'http://%s:%s@%s/%s' % (self.userid,self.password,self.hostname,url))
49        curl.setopt(curl.WRITEFUNCTION, self.body_callback)
50        try:
51            curl.perform()
52            curl.close()
53        except pycurl.error:
54            return None
55        return self.contents
56    def off(self,outlet=0):
57        """ Turn off a power to an outlet """
58        self.geturl(url= 'outlet?%d=OFF' % outlet)
59    def on(self,outlet=0):
60        """ Turn on power to an outlet """
61        self.geturl(url= 'outlet?%d=ON' % outlet)
62    def statuslist(self):
63        """ Return the status of all outlets in a list,
64        each item will contain 3 itmes plugnumber, hostname and state  """
65        outlets=[]
66        url=self.geturl('index.htm')
67        if not url:
68            return None
69        soup=BeautifulSoup.BeautifulSoup(url)
70        try:
71            powertable=soup.findAll('table')[5]
72        except IndexError:
73            return None
74        for temp in powertable.findAll('tr')[2:]:
75            columns=temp.findAll('td')
76            plugnumber=columns[0].string
77            hostname=columns[1].string
78            state=columns[2].find('font').string
79            outlets.append([int(plugnumber),hostname,state])
80        return outlets
81    def printstatus(self):
82        """ Print the status off all the outlets as a table to stdout """
83        if not self.statuslist():
84            print "Unable to communicte to the Web power switch at %s" % self.hostname
85            return None
86        print 'Outlet\t%-15.15s\tState' % 'Hostname'
87        for item in self.statuslist():
88            print '%d\t%-15.15s\t%s' % (item[0],item[1],item[2])
89    def status(self,outlet=1):
90        """ Return the status of an outlet, returned value will be one of: On, Off, Unknown """
91        outlets=self.statuslist()
92        if outlet:
93            for plug in outlets:
94                if plug[0] == outlet:
95                    return plug[2]
96        return 'Unknown'
97
98if __name__ == "__main__":
99    parser = optparse.OptionParser()
100    parser.add_option('--hostname',dest='hostname',default="192.168.0.100")
101    parser.add_option('--user',    dest='user',    default="admin")
102    parser.add_option('--password',dest='password',default="4321")
103    (options, args) = parser.parse_args()
104
105    switch=powerswitch(userid=options.user,password=options.password,hostname=options.hostname)
106    if len(args):
107        if len(args) == 2:
108            if args[0].lower() in ['on','poweron']:
109                switch.on(int(args[1]))
110            if args[0].lower() in ['off','poweroff']:
111                switch.off(int(args[1]))
112            if args[0].lower() in ['status']:
113                print switch.status(int(args[1]))
114    else:
115        switch.printstatus()
116