예제 #1
0
    def do_GET(self):
##        if os.environ.get('REQUEST_METHOD','').lower()=='get' :
##        form = os.environ.get('QUERY_STRING', '')
##        if os.environ['QUERY_STRING']:
##            form = cgi.FieldStorage()
##        else:
##            form = None
##        cgi.print_environ()
##        fp=self.rfile
##        headers=self.headers
##        env = environ.get('REQUEST_METHOD':'GET','QUERY_STRING', None)
##        'CONTENT_TYPE':self.headers['Content-Type'],}
##        form = cgi.FieldStorage(fp,headers,env)
##        form = cgi.FieldStorage()                   #ani jedna verze nefunguje
##        s = HTTPHandler.processRequest(self.path, form)

        parsed_path = urlparse.urlparse(self.path)
        query = urlparse.parse_qs(parsed_path.query)    #nacteni parametru do dictionary
        try:
            params = dict([p.split('=') for p in parsed_path[4].split('&')])
        except:
            params = {}

        s = HTTPHandler.processRequest(parsed_path[2], params)
        if (s[1] != None):
            try:
                #Open the static file requested and send it
                self.send_response(200)
                self.send_header('Content-type',s[1])
                self.end_headers()
                self.wfile.write(s[0])
                return
            except IOError:
                self.send_error(404,'File Not Found: %s' % self.path)
 def __init__(self, host, username, password, verbose=False):
     """
     """
     self.verbose = verbose
     self.routers = {
                     'MessagingRouter': 'messaging',
                     'EventsRouter': 'evconsole',
                     'ProcessRouter': 'process',
                     'ServiceRouter': 'service',
                     'DeviceRouter': 'device',
                     'NetworkRouter': 'network',
                     'TemplateRouter': 'template',
                     'DetailNavRouter': 'detailnav',
                     'ReportRouter': 'report',
                     'MibRouter': 'mib',
                     'ZenPackRouter': 'zenpack' 
                     }
     self.host = host
     self.username = username
     self.password = password
     self.baseurl = "http://%s:8080" % self.host
     self.login = {
                   "__ac_name": self.username,
                   "__ac_password": self.password,
                   "submitted": "true",
                   "came_from": "%s/zport/dmd" % self.baseurl
                   }
     self.buffersize = 50
     self.http = HTTPHandler()
     self.http.verbose = verbose
     self.http.persist("%s/zport/acl_users/cookieAuthHelper/login" % self.baseurl ,self.login)
예제 #3
0
 def accept(self, sock: socket.socket):
     conn, addr = sock.accept()
     conn.setblocking(False)
     self.log.log('accept connection to' + repr(addr))
     handler = HTTPHandler.Handler(self.selector, conn, addr, self.log,
                                   self.db_handler)
     self.selector.register(conn, selectors.EVENT_READ, data=handler)
예제 #4
0
    def do_POST(self):
        form = cgi.FieldStorage(fp=self.rfile,
                                headers=self.headers,
                                environ={
                                    'REQUEST_METHOD': 'POST',
                                    'CONTENT_TYPE':
                                    self.headers['Content-Type'],
                                })

        names = []
        values = []
        for i in form.list:
            names.append(i.name)
            values.append(i.value)
        dictionary = dict(zip(names, values))  #prevod parametru do dictionary

        s = HTTPHandler.processRequest(self.path, dictionary)
        if (s[1] != None):
            try:
                self.send_response(200)
                self.send_header('Content-type', s[1])
                self.end_headers()
                self.wfile.write(s[0])
                return
            except IOError:
                self.send_error(404, 'File Not Found: %s' % self.path)
예제 #5
0
    def do_GET(self):
        ##        if os.environ.get('REQUEST_METHOD','').lower()=='get' :
        ##        form = os.environ.get('QUERY_STRING', '')
        ##        if os.environ['QUERY_STRING']:
        ##            form = cgi.FieldStorage()
        ##        else:
        ##            form = None
        ##        cgi.print_environ()
        ##        fp=self.rfile
        ##        headers=self.headers
        ##        env = environ.get('REQUEST_METHOD':'GET','QUERY_STRING', None)
        ##        'CONTENT_TYPE':self.headers['Content-Type'],}
        ##        form = cgi.FieldStorage(fp,headers,env)
        ##        form = cgi.FieldStorage()                   #ani jedna verze nefunguje
        ##        s = HTTPHandler.processRequest(self.path, form)

        parsed_path = urlparse.urlparse(self.path)
        query = urlparse.parse_qs(
            parsed_path.query)  #nacteni parametru do dictionary
        try:
            params = dict([p.split('=') for p in parsed_path[4].split('&')])
        except:
            params = {}

        s = HTTPHandler.processRequest(parsed_path[2], params)
        if (s[1] != None):
            try:
                #Open the static file requested and send it
                self.send_response(200)
                self.send_header('Content-type', s[1])
                self.end_headers()
                self.wfile.write(s[0])
                return
            except IOError:
                self.send_error(404, 'File Not Found: %s' % self.path)
예제 #6
0
def setupServer():
	"""
	This function creates a Webpy server obect and begins to run that server.

	Parameters:
	None

	Returns:
	None
	"""
	server = HTTPHandler.homeScreen() #Creates a new instance of the server.
	server.app.run() #Runs the server if server.py is the file being called. WILL NOT WORK IF SERVER.PY IS BEING CALLED AS A MODULE.
 def __init__(self, host, token, verbose=False):
     """
     """
     self.verbose = verbose
     self.host = host
     self.token = token
     self.incidentEndpoint = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
     self.weburl = "https://%s" % self.host
     self.baseurl = "https://%s/api/v1" % self.host
     self.buffersize = 50
     self.http = HTTPHandler()
     self.http.verbose = verbose
     self.http.headers["Content-type"] = "application/json"
예제 #8
0
    def __init__(self):
        ''' doc '''
        print 'loading...'
        self.username = raw_input('Please enter your EID: ')
        self.password = getpass.getpass('Please enter your windows password: ')
        self.url_sasn_program = URL_PL_SASN_PROGRAM
        self.srcURL = None
        self.featureBranch = None
        self.cmpURL = URL_LSV_PROGRAM
        self.finalReportPath = FINAL_REPORT_PATH
        self.firstTestReportPath = FIRST_TEST_REPORT_PATH
        self.LSVReportPath = LSV_FINAL_REPORT_PATH
        self.createFinalReportPath = CREATE_FINAL_REPORT_PATH
        self.savedReportPath = URL_SAVED_REPORT
        self.templatePath = TEMPLATE_PATH
        self.finalPath = FINAL_PATH
        self.resultPath = RESULT_PATH
        self.pipeLineInfo = {}

        self.httpHandler = HTTPHandler.HTTPHandler(URL_LOG_IN, self.username,
                                                   self.password)
        self.myHTMLParser = HTTPHandler.HTMLHandler()
        self.contentProcessor = ContentProcessor.ContentProcessor()
예제 #9
0
    def do_POST(self):
        form = cgi.FieldStorage(fp=self.rfile,headers=self.headers,environ={'REQUEST_METHOD':'POST','CONTENT_TYPE':self.headers['Content-Type'],})

        names=[]
        values=[]
        for i in form.list:
            names.append(i.name)
            values.append(i.value)
        dictionary = dict(zip(names, values))   #prevod parametru do dictionary

        s = HTTPHandler.processRequest(self.path, dictionary)
        if (s[1] != None):
            try:
                self.send_response(200)
                self.send_header('Content-type',s[1])
                self.end_headers()
                self.wfile.write(s[0])
                return
            except IOError:
                self.send_error(404,'File Not Found: %s' % self.path)
예제 #10
0
    def __init__(self):
        '''
        Constructor
        '''
        self.logFoundPa = re.compile('REGRESSION RESULTS')
        self.myHTMLParser = HTTPHandler.HTMLHandler()
        self.content = None

        self.patterns = [
            (
                re.compile('CHANGES/FIXES [A-Z :<>/tdrb-]+'),
                # start of content of CHANGES/FIXES SINCE PREVIOUS BUILD
                re.compile('<tr><td>-+[\r<>/tdrb ]+REGRESSION RESULTS')),
            # end of content of CHANGES/FIXES SINCE PREVIOUS BUILD
            (
                re.compile('REGRESSION RESULTS:'),
                #start of content of REGRESSION RESULTS
                re.compile('<tr><td>-+[\r<>/tdrb ]+FUNCTIONAL TESTS')),
            # end of content of REGRESSION RESULTS
        ]
class ZenossHandler():
    """
    """
    def __init__(self, host, username, password, verbose=False):
        """
        """
        self.verbose = verbose
        self.routers = {
                        'MessagingRouter': 'messaging',
                        'EventsRouter': 'evconsole',
                        'ProcessRouter': 'process',
                        'ServiceRouter': 'service',
                        'DeviceRouter': 'device',
                        'NetworkRouter': 'network',
                        'TemplateRouter': 'template',
                        'DetailNavRouter': 'detailnav',
                        'ReportRouter': 'report',
                        'MibRouter': 'mib',
                        'ZenPackRouter': 'zenpack' 
                        }
        self.host = host
        self.username = username
        self.password = password
        self.baseurl = "http://%s:8080" % self.host
        self.login = {
                      "__ac_name": self.username,
                      "__ac_password": self.password,
                      "submitted": "true",
                      "came_from": "%s/zport/dmd" % self.baseurl
                      }
        self.buffersize = 50
        self.http = HTTPHandler()
        self.http.verbose = verbose
        self.http.persist("%s/zport/acl_users/cookieAuthHelper/login" % self.baseurl ,self.login)

    def request(self,router,method,data=[]):
        """
            Handle HTTP GET / POST operations against Zenoss API
        """
        self.http.headers['Content-type'] = 'application/json; charset=utf-8'
        self.http.connect("%s/zport/dmd/%s_router" % (self.baseurl,self.routers[router]))
        data = {
                "action": router,
                "method": method,
                "data": data,
                "type": 'rpc',
                "tid" : self.http.counter
                }
        self.http.transact(data)
        return self.http.response
        
    def getEvents(self, history=False, open=False):
        """
            retrieve current console events
        """
        if self.verbose is True: print "Getting list of console events with history: %s and open: %s" % (history, open)
        data = dict(start=0, limit=self.buffersize, dir='DESC', sort='lastTime')
        # get results from history
        if history is True: data['history'] = True
        # only get open events
        if open is True: data['params'] = dict(eventState=[0,1], severity=[5,4,3])
        else: data['params'] = dict(severity=[5,4,3,0])
        return self.request('EventsRouter','query',[data])["result"]
    
    def manageEventStatus(self, evids=[], action="acknowledge"):
        """
            manage event status
            action = [acknowledge|close]
        """
        if self.verbose is True: print "Changing event status to %s for evids: %s" % (action, ', '.join(evids))
        data = [{"evids": evids}]
        return self.request('EventsRouter',action,data)
    
    def addEventMessage(self, evid, message):
        """
            manage event open/close/acknowledge status
        """
        if self.verbose is True: print 'Adding message: "%s" to event: %s' % (message, evid)
        data = {
                'evid': evid,
                'message':message
                }
        return self.request('EventsRouter','write_log',[data])
      
    def getEventDetails(self, evid, history=False):
        """
            manage event open/close/acknowledge status
        """
        if self.verbose is True: print "Getting event details for %s with history: %s" % (evid, history)
        data = {
                'evid': evid,
                }
        if history == True:
            data['history'] = 'True'
        return self.request('EventsRouter','detail',[data])
예제 #12
0
파일: main.py 프로젝트: rakane/RoomMapping
import time
from SerialHandler import *
from MapHandler import *
from HTTPHandler import *

plotHost = '192.168.1.129'
plotPort = '5000'

serialHandler = SerialHandler()
mapHandler = MapHandler()
httpHandler = HTTPHandler(plotHost, plotPort)

# Center Distance 140 + or - 2

while True:
    i = 50
    while i < 231:
        # Measurement command test
        print("------------------------------")
        print("Requesting measurement at angle of", end=' ')
        print(i, end='')
        print("...")
        distance = serialHandler.getDistance(i)
        if (distance < 0):
            if (distance == -1):
                print("Error! Angle measurement invalid")
                serialHandler.resetSensorMotor()
                i -= 10
            else:
                print("Error, no response from Arduino")
                exit(1)
class PagerDutyHandler:
    """
        Python wrapper for PagerDuty WWW API
    """

    def __init__(self, host, token, verbose=False):
        """
        """
        self.verbose = verbose
        self.host = host
        self.token = token
        self.incidentEndpoint = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
        self.weburl = "https://%s" % self.host
        self.baseurl = "https://%s/api/v1" % self.host
        self.buffersize = 50
        self.http = HTTPHandler()
        self.http.verbose = verbose
        self.http.headers["Content-type"] = "application/json"

    def request(self, endpoint, data=None, token=True, method="GET"):  # data should be list of dicts
        """
            Handle HTTP GET / POST operations against PagerDuty API
        """
        if data and method == "GETARG":
            endpoint += "?%s" % urllib.urlencode(data)
        if token == True:
            self.http.headers["Authorization"] = "Token token=%s" % self.token
        self.http.connect(endpoint)
        if data:
            if method == "POST":
                self.http.post(data)
            if method == "PUT":
                self.http.put(data)
            if method == "GET":
                self.http.session.add_data(json.dumps(data))
        self.http.submit()
        return self.http.response

    def manageIncident(self, data, action="trigger"):
        """
            action = [trigger|acknowledge|resolve] 
            Manage PagerDuty Incidents
        """
        if self.verbose is True:
            print "Managing %s Incident with %s" % (action, data)
        data["event_type"] = action
        output = self.request(self.incidentEndpoint, data, token=False, method="POST")
        return output

    def updateStatus(self, data):
        """
            action = [trigger|acknowledge|resolved] 
            Manage PagerDuty Incidents
        """
        if self.verbose is True:
            print "Updating status with %s" % (data)
        return self.request("%s/incidents" % self.baseurl, data, token=True, method="PUT")

    def getServiceList(self):
        """
            Retrive list of services
        """
        if self.verbose is True:
            print "Getting list of services"
        return self.request("%s/services" % self.baseurl)

    def getServiceDetail(self, id):
        """
            Retrive details for service
        """
        if self.verbose is True:
            print "Getting service details for %s" % id
        return self.request("%s/services/%s" % (self.baseurl, id))

    def getServiceLog(self, id):
        """
            Retrive logs for service
        """
        if self.verbose is True:
            print "Getting service log for %s" % id
        return self.request("%s/services/%s/log" % (self.baseurl, id))

    def getIncidentList(self, open=False):
        """
            Retrive list of all incidents
        """
        if self.verbose is True:
            print "Getting list of ALL incidents"
        data = {"sort_by": "created_on:desc", "limit": self.buffersize}
        if open is True:
            data["status"] = "triggered,acknowledged"
        return self.request("%s/incidents" % self.baseurl, data, token=True, method="GETARG")

    def getIncidentByKey(self, key):
        """
            Retrieve incident by its incident key
        """
        if self.verbose is True:
            print "Getting incident details for key: %s" % key
        data = {"incident_key": key}
        return self.request("%s/incidents" % self.baseurl, data, token=True, method="GETARG")

    def getIncidentDetail(self, id):
        """
            return incident details given the ID
        """
        if self.verbose is True:
            print "Getting incident details for id: %s" % id
        return self.request("%s/incidents/%s/log_entries" % (self.baseurl, id))

    def getIncidentLog(self, id):
        """
            return incident log given the ID
        """
        if self.verbose is True:
            print "Getting incident details for log: %s" % id
        return self.request("%s/incidents/%s/log" % (self.baseurl, id))

    def getMaintenanceWindows(self):
        """
            return maintenance window information
        """
        if self.verbose is True:
            print "Getting list of maintenance windows"
        # data = {"type":"ongoing"}
        return self.request("%s/maintenance_windows" % self.baseurl)

    def findService(self, serviceKey):
        """
            find service info for given key
        """
        if self.verbose is True:
            print "Finding service for key: %s" % serviceKey
        services = self.getServiceList()
        for s in services["services"]:
            if s["service_key"] == serviceKey:
                return s
        return None

    def getServiceStatus(self, data):
        """ Return the servcie status"""
        if self.verbose is True:
            print "Getting service status for %s" % data
        return data["status"]

    def inMaintenance(self, data):
        """ Return True if service is in maintenance"""
        if self.verbose is True:
            print "Getting maintenance status for %s" % data
        if self.getServiceStatus(data) == "maintenance":
            return True
        return False

    def isDisabled(self, data):
        """ Return True if service is disabled"""
        if self.verbose is True:
            print "Getting disabled status for %s" % data
        if self.getServiceStatus(data) == "disabled":
            return True
        return False

    def isActive(self, data):
        """ Return True if service is active"""
        if self.verbose is True:
            print "Getting active status for %s" % data
        if self.getServiceStatus(data) == "active":
            return True
        return False