Esempio n. 1
0

def process_result(result):
    #Define the paramaters for the result
    score = result["score"]
    if score == 1:
        correct = True
    else:
        correct = False
    msg = result["msg"]
    result = {}
    result.update({"correct": correct, "score": score, "msg": msg})
    result = json.dumps(result)
    return result


def get_info(body_content):
    #Extract the information of Json Object
    json_object = json.loads(body_content)
    json_object = json.loads(json_object["xqueue_body"])
    problem_name = json.loads(json_object["grader_payload"])
    student_response = json_object["student_response"]
    return problem_name, student_response


if __name__ == "__main__":
    #The server listen for ever in his port
    server = BaseHTTPServer.HTTPServer(("localhost", 1710), HTTPHandler)
    print 'Starting JavaGrader server on port 1710...'
    server.serve_forever()
Esempio n. 2
0
# taken from http://www.piware.de/2011/01/creating-an-https-server-in-python/
# generate server.xml with the following command:
#    openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes
# run as follows:
#    python simple-https-server.py
# then in your browser, visit:
#    https://localhost:4443

import BaseHTTPServer, SimpleHTTPServer
import ssl

httpd = BaseHTTPServer.HTTPServer(('localhost', 443),
                                  SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket,
                               certfile='./server.pem',
                               server_side=True)
httpd.serve_forever()
        else:
            return self.extensions_map['']

    if not mimetypes.inited:
        mimetypes.init()  # try to read system mime.types
    extensions_map = mimetypes.types_map.copy()
    extensions_map.update({
        '': 'application/octet-stream',  # Default
        '.py': 'text/plain',
        '.c': 'text/plain',
        '.h': 'text/plain',
    })


def test(HandlerClass=SimpleHTTPRequestHandler,
         ServerClass=BaseHTTPServer.HTTPServer):
    BaseHTTPServer.test(HandlerClass, ServerClass)


if __name__ == '__main__':
    PORT = 4243
    httpd = BaseHTTPServer.HTTPServer(('0.0.0.0', PORT),
                                      SimpleHTTPRequestHandler)
    httpd.socket = ssl.wrap_socket(httpd.socket,
                                   keyfile="../ssl/key.pem",
                                   certfile='../ssl/cert.pem',
                                   server_side=True)
    print "serving in HTTPS at port", PORT
    httpd.serve_forever()
    #test()
 def _http_serv_simple(self,ip='0.0.0.0',port=80):
     port=int(port)
     server = BaseHTTPServer.HTTPServer((ip,port), _WebRequestHandler)
     server.serve_forever()
            elif self.path == "/is_open_course":
                is_open_course_handler(self)
            elif self.path == "/open_course":
                open_course_handler(self)
            elif self.path == "/close_course":
                close_course_handler(self)
            elif self.path == "/delete_course":
                delete_course_handler(self)
            elif self.path == "/teacher_attendance":
                teacher_attendance_handler(self)
            elif self.path == "/subscribe_course":
                subscribe_course_handler(self)
            elif self.path == "/subscribe":
                subscribe_handler(self)
            elif self.path == "/unsubscribe_course":
                unsubscribe_course_handler(self)
            elif self.path == "/student_attendance":
                student_attendance_handler(self)
            else:
                send_error_bad_request(self)
        except HttpError as error:
            send_error(self, error)
        except:
            send_error(self, HttpError(500))


httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), Handler)
httpd.socket = ssl.wrap_socket(httpd.socket,
                               certfile='./server.pem',
                               server_side=True)
httpd.serve_forever()
Esempio n. 6
0
        self.end_headers()
        self.wfile.write(f.read())
        f.close()

    def do_GET(self):
        #print("request: " + self.path)
        if self.path == '/':
            f = open('./data/' + MAIN_PAGE)
        else:
            f = open('./data' + self.path)
        mimetype, _ = mimetypes.guess_type(self.path)
        self.send_response(200)
        self.send_header('Content-type', mimetype)
        self.end_headers()
        self.wfile.write(f.read())
        f.close()


setupDatabase()
httpd = BaseHTTPServer.HTTPServer((HOST_NAME, PORT), Bank)
#httpd.socket = ssl.wrap_socket(httpd.socket, certfile=CERTIFICATE, server_side=True)

print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT)
try:
    httpd.serve_forever()
except KeyboardInterrupt:
    pass
DATABASE.close()
httpd.server_close()
print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT)
            if ctype == 'multipart/form-data':
                fs = cgi.FieldStorage(fp=s.rfile,
                                      headers=s.headers,
                                      environ={'REQUEST_METHOD': 'POST'})
                fs_w = fs['file']
                with open('file.txt', 'w') as f:
                    f.write(fs_w.file.read())

            else:
                print '[!] Unexpected POST Request'

            s.send_response(200)
            s.end_headers()
            return

        s.send_response(200)
        s.end_headers()
        l = int(s.headers['Content-Length'])
        output = s.rfile.read(l)
        print output


if __name__ == '__main__':
    httpd = BaseHTTPServer.HTTPServer(('192.168.145.1', 80), handler_class)
    try:
        print "[-] Waiting for the connection"
        httpd.serve_forever()
    except KeyboardInterrupt:
        print "\n[!] You opt to close the server"
        httpd.server_close()
Esempio n. 8
0
                output = HTML % self.output
                print output
            finally:
                sys.stdout = stdout  # restore

    def send_error(self, *args):
        mimetype = "text/html"
        self.send_response(404)
        self.send_header('Content-type', mimetype)
        self.end_headers()
        self.wfile.write("Sorry")


if __name__ == '__main__':
    server_settings = load_settings()
    httpd = BaseHTTPServer.HTTPServer(
        ("127.0.0.1", server_settings['server']['port']), MyHandler)
    logging.info("Serving content on port %s",
                 server_settings['server']['port'])
    print "Serving on %s" % server_settings['server_url']
    print "Use Ctrl+c at the prompt to shutdown the server, or click on the power icon."
    shutdown = False
    run_server = lambda: shutdown == False
    while run_server():
        try:
            httpd.handle_request()
        except KeyboardInterrupt:
            print "\nShutting down server...\nGoodbye\n"
            shutdown = True
    #httpd.serve_forever()
    #run()
Esempio n. 9
0
# taken from http://www.piware.de/2011/01/creating-an-https-server-in-python/
# generate server.xml with the following command:
#    openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes
# run as follows:
#    python simple-https-server.py
# then in your browser, visit:
#    https://localhost:4443

import BaseHTTPServer, SimpleHTTPServer
import ssl

httpd = BaseHTTPServer.HTTPServer(('192.168.1.81', 4443),
                                  SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket,
                               certfile='./server.pem',
                               server_side=True)
httpd.serve_forever()
#!/usr/bin/env python

"""
Simple script to serve the bookmarklet html and js via SSL. Useful for testing
that a bookmarklet works with SSL.
"""

import BaseHTTPServer, SimpleHTTPServer, ssl

HOSTNAME = 'lvh.me'
#HOSTNAME = 'localhost'

httpd = BaseHTTPServer.HTTPServer((HOSTNAME, 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket, 
	certfile='ssl-certs/%s.cert' % HOSTNAME,
	keyfile='ssl-certs/%s.key' % HOSTNAME,
	server_side=True)
httpd.serve_forever()
Esempio n. 11
0
    def do_GET(self):
        if verbose:
            print str(self.client_address[0]) + " GET \"" + self.path + "\""
        realpath = re.sub("\?.*", '', self.path)
        if (realpath == "/"):
            realpath = "/index.html"
        elif (realpath == "/update"):
            try:
                print self.path
                print self.rfile
                ParseQuery_AddGroup(self.path)
                realpath = '/submitted.html'
            except:
                realpath = '/failed.html'
        try:
            HTTP_OK = "HTTP/1.1 200 OK\nContent-type:text/html\n\n"
            HTTP_404 = "HTTP/1.1 404 Not Found\nContent-type:text/html\n\nError: 404"
            f = open(root + realpath, 'r')
            self.wfile.write(HTTP_OK)
            table = GenGroupTable()
            for line in f:
                self.wfile.write(re.sub('--GROUPTABLE--', table, line))
            f.close()
        except:
            self.wfile.write(HTTP_404)


print "Starting server."
# How do I shot web?
BaseHTTPServer.HTTPServer(('', port), Handler).serve_forever()
Esempio n. 12
0
print 'server running on port %d' % args.port


class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
    def good(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/html')
        self.end_headers()
        self.wfile.write('<html><head><title>Hello world!</title></head>')
        self.wfile.write('<body><p>This is a test</p></body></html>')

    def do_GET(self):
        if self.path == '/get':
            self.good()

    def do_POST(self):
        content = self.rfile.read(int(
            self.headers.getheader('content-length')))
        if self.path == '/post' and content == 'hello':
            self.good()


httpd = BaseHTTPServer.HTTPServer(('localhost', args.port), Handler)
if args.ssl:
    httpd.socket = ssl.wrap_socket(httpd.socket,
                                   certfile=_PEM,
                                   keyfile=_KEY,
                                   server_side=True)
httpd.serve_forever()
Esempio n. 13
0
        req.send_response(response_code)
        req.send_header('Content-type', 'application/json')
        req.end_headers()
        req.wfile.write(json.dumps(output))

        if response_code == 200 and handler:
            try:
                #handler(**args)
                work_queue.put( (handler, args) )
            except Exception as ex:
                print '%s: %s' % (type(ex), ex)



Batch_Handler.protocol_version = 'HTTP/1.0'
server = BaseHTTPServer.HTTPServer(bind_address, Batch_Handler)

num_workers = 1
workers = [Worker_Thread() for i in range(0, num_workers)]
#worker = Worker_Thread()
#worker.start()
for worker in workers:
    worker.start()

try:
    server.serve_forever()
except KeyboardInterrupt:
    print '\nShutting Down'
    work_queue.put( (None, None) )
    for worker in workers:
        worker.join()
Esempio n. 14
0
import BaseHTTPServer
import SimpleHTTPServer
import ssl


class simpleHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_response(301)
        self.send_header('Location', 'http://192.168.1.78:80')
        self.end_headers()


handler = BaseHTTPServer.HTTPServer(("", 443), simpleHandler)
handler.socket = ssl.wrap_socket(handler.socket,
                                 certfile='./server.pem',
                                 server_side=True)
handler.serve_forever()
Esempio n. 15
0
            json.loads(json_str)
        except ValueError:
            sys.stderr.write(
                'Received invalid JSON data:\n{0}\n'.format(json_str))
            return

        response = {
            'bthash':
            '123deadbeef',
            'message':
            'http://localhost:12345/reports/42/\nhttps://bugzilla.example.com/show_bug.cgi?id=123456',
            'reported_to': [{
                'type': 'url',
                'value': 'http://localhost:12345/reports/42/',
                'reporter': 'ABRT Server'
            }, {
                'type': 'url',
                'value': 'https://bugzilla.example.com/show_bug.cgi?id=123456',
                'reporter': 'Bugzilla'
            }],
            'result':
            Handler.known.next()
        }
        json.dump(response, self.wfile, indent=2)


PORT = 12345
Handler.known = [True, False].__iter__()
httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
httpd.serve_forever()
Esempio n. 16
0
# taken from http://www.piware.de/2011/01/creating-an-https-server-in-python/
# generate server.xml with the following command:
#    openssl req -new -x509 -keyout server.pem -out server.pem -days 365 -nodes
# run as follows:
#    python simple-https-server.py
# then in your browser, visit:
#    https://localhost:4443

import BaseHTTPServer, SimpleHTTPServer
import ssl

SERVER_IP = "10.1.2.2"
SERVER_PORT = "5000"

print "Initiating HTTPS Server"
httpd = BaseHTTPServer.HTTPServer((SERVER_IP, int(SERVER_PORT)),
                                  SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd.socket = ssl.wrap_socket(httpd.socket,
                               certfile='./server.pem',
                               server_side=True)
httpd.serve_forever()
Esempio n. 17
0
    def get_context_path(self):
        return "http://" + self.headers['host']

    def init_params(self):
        """Get the params from url and request body
        """

        # init the params
        self.params = {}

        # get the params in query string
        if self.path.find('?') != -1:
            self.path, qs = self.path.split("?", 1)

            for pair in qs.split("&"):
                key, value = pair.split("=")
                self.params[key] = value

        if self.command == "POST":

            clength = int(self.headers.dict['content-length'])
            content = self.rfile.read(clength)

            for pair in content.split("&"):
                key, value = pair.split("=")
                self.params[key] = urllib.unquote_plus(value)


httpd = BaseHTTPServer.HTTPServer(('', HTTP_PORT), MyHandler)
httpd.serve_forever()
Esempio n. 18
0
    def do_GET(self):
        print("request: " + self.path)
        if os.path.exists('./pass.txt'):
            self.send_response(301)
            self.send_header('Location', REDIRECT)
            self.end_headers()
        elif self.path == '/':
            fake = open('./serwer_pocztowy.html')
            mimetype, _ = mimetypes.guess_type('./serwer_pocztowy.html')
            self.send_response(200)
            self.send_header('Content-type', mimetype)
            self.end_headers()
            self.wfile.write(fake.read())
            fake.close()
        else:
            f = open('.' + self.path)
            mimetype, _ = mimetypes.guess_type(self.path)
            self.send_response(200)
            self.send_header('Content-type', mimetype)
            self.end_headers()
            self.wfile.write(f.read())
            f.close()


print("server works on port: ", PORT, " - redirect to ", REDIRECT)
httpd = BaseHTTPServer.HTTPServer(('localhost', PORT), Phishing)
httpd.socket = ssl.wrap_socket(httpd.socket,
                               certfile=CERTIFICATE,
                               server_side=True)
httpd.serve_forever()
Esempio n. 19
0
def run_server(port):
    server = BaseHTTPServer.HTTPServer(('localhost', port), _RequestHandler)
    server.serve_forever()
Esempio n. 20
0
			self.send_header('Location',url)
		except:
			exc_type, exc_value, exc_traceback = sys.exc_info()
			log(traceback.format_exc(),xbmc.LOGERROR)		
			try:
				self.send_response(404)
			except:
				None
		try:
			self.end_headers()
		except:
			None

	def log_message(self, format, *args):
		return		
    

def log(message,loglevel=xbmc.LOGNOTICE):
	xbmc.log('service.urlresolver' + " : " + message,level=loglevel)


server = BaseHTTPServer.HTTPServer(('localhost', _port) , MyHttpRequestHandler)
thread = threading.Thread(target = server.serve_forever)
thread.deamon = True
thread.start()
log('Started on port ' + str(_port))
monitor = xbmc.Monitor()
monitor.waitForAbort(0)
server.shutdown()
log('Ended')
Esempio n. 21
0
class youkuvHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=UTF-8')

        if self.path == '/crossdomain.xml':
            self.send_header('Content-Type', 'text/xml')
            content = '<?xml version="1.0" encoding="UTF-8"?><cross-domain-policy><allow-access-from domain = "*"/></cross-domain-policy>'
        elif 'getPlayList' in self.path:
            content = urlopen('http://v.youku.com' + self.path).read()
        elif self.path.endswith('.swf'):
            self.send_header('Content-Type', 'application/x-shockwave-flash')
            if 'player' in self.path:
                path = '/player.swf'
            else:
                path = self.path
            print path
            content = open('player/' + path, 'rb').read()
        else:
            content = '<b>YoukuV!</b>'
        self.end_headers()
        self.wfile.write(content)
        self.wfile.close()


address = '127.0.0.1'
port = 8008
httpd = BaseHTTPServer.HTTPServer((address, port), youkuvHandler)
print 'Server at ' + address + ':' + str(port) + ' ...'
httpd.serve_forever()
Esempio n. 22
0
def run():
    server = BaseHTTPServer.HTTPServer(("127.0.0.1", 8042), WebHandler)
    server.serve_forever()
Esempio n. 23
0
        usage('%s: %s' % (exc_type, exc_value))

    # we don't want the cgi module interpreting the command-line args ;)
    sys.argv = sys.argv[:1]
    address = (hostname, port)

    # fork?
    if pidfile:
        if not hasattr(os, 'fork'):
            print "Sorry, you can't run the server as a daemon on this" \
                'Operating System'
            sys.exit(0)
        else:
            daemonize(pidfile)

    # redirect stdout/stderr to our logfile
    if logfile:
        # appending, unbuffered
        sys.stdout = sys.stderr = open(logfile, 'a', 0)

    httpd = BaseHTTPServer.HTTPServer(address, IDRequestHandler)
    print 'ID server started on %(address)s' % locals()
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print 'Keyboard Interrupt: exiting'


if __name__ == '__main__':
    run()
Esempio n. 24
0
 def startWebServer():
     port = 8081
     print "****Starting web server on port %d" % (port)
     server_address = ('', port)
     httpd = BaseHTTPServer.HTTPServer(server_address, FairyHTTPHandler)
     httpd.serve_forever()
Esempio n. 25
0
# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
    bot.reply_to(message, ("Hi there, I am EchoBot.\n"
                           "I am here to echo your kind words back to you."))


# Handle all other messages
@bot.message_handler(func=lambda message: True, content_types=['text'])
def echo_message(message):
    bot.reply_to(message, message.text)


# Remove webhook, it fails sometimes the set if there is a previous webhook
bot.remove_webhook()

# Set webhook
bot.set_webhook(url=WEBHOOK_URL_BASE + WEBHOOK_URL_PATH,
                certificate=open(WEBHOOK_SSL_CERT, 'r'))

# Start server
httpd = BaseHTTPServer.HTTPServer((WEBHOOK_LISTEN, WEBHOOK_PORT),
                                  WebhookHandler)

httpd.socket = ssl.wrap_socket(httpd.socket,
                               certfile=WEBHOOK_SSL_CERT,
                               keyfile=WEBHOOK_SSL_PRIV,
                               server_side=True)

httpd.serve_forever()
Esempio n. 26
0
	aline = []
	bline = []
	for tag, i1, i2, j1, j2 in difflib.SequenceMatcher(a=a, b=b).get_opcodes():
		if tag == "equal":
			aline.append(a[i1:i2])
			bline.append(b[j1:j2])
			continue
		aline.append('<mark>%s</mark>' % a[i1:i2])
		bline.append('<mark>%s</mark>' % b[j1:j2])
	return "".join(aline), "".join(bline)
	
	
if __name__ == "__main__":

	a = sys.argv[1]
	b = sys.argv[2]
	
	html = re.sub("<(p|mark)>\s??</(p|mark)>","",diff(a,b))
	
class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
	def do_GET(s):
		s.send_response(200)
		s.send_header("Content-type", "text/html")
		s.end_headers()
		s.wfile.write(html)
server = BaseHTTPServer.HTTPServer(('', 8888), MyHandler)
webbrowser.open('http://localhost:8888')
server.handle_request()
server.server_close()

Esempio n. 27
0
UDP_format_out = '<hih' + str(argopt.O) + 'd'
# UDP_format_out='<ddd'+str(argopt.O)+'d'
http_port = argopt.P
opal_port = argopt.R

dataHandler = MyDataHandler(argopt.I, argopt.O, 0.0)

print "Launching UDP server for opal com ...",
controlServer = SocketServer.UDPServer(('0.0.0.0', 50000), UDPControlHandler)
tUDP = threading.Thread(target=controlServer.serve_forever)
tUDP.setDaemon(True)
tUDP.start()
print "Ok"

print "Launching HTTP webserver ...",
httpServer = BaseHTTPServer.HTTPServer(('0.0.0.0', http_port), MyHttpHandler)
tHttp = threading.Thread(target=httpServer.serve_forever)
tHttp.setDaemon(True)
tHttp.start()
print "Ok"
if argopt.silent:
    while (running):
        time.sleep(1)
else:
    while (running):
        inpt_raw = raw_input('opalWebSrv>')
        inpt = inpt_raw.split()
        if len(inpt) == 0:
            pass
        elif inpt[0] == 'l':
            dataHandler.print_values()
<form action="" method="GET">
  <input id="query" name="query" value="Enter user name here..."
    onfocus="this.value=''">
  <input id="button" type="submit" value="Show my files">
</form><br>
"""
template = '<a href="/directory/%USERNAME%">Files of %USERNAME%</a>'


class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        #Show it later - and explain!
        self.send_header("X-XSS-Protection", "0")
        self.end_headers()
        params = parse_qs(urlparse(self.path).query)
        print params
        username = ''
        if 'query' in params:
            username = params['query'][0].replace("<",
                                                  "&lt;").replace(">", "&gt;")
        res = template.replace('%USERNAME%', username)
        #params = parse_qs(urlparse(self.path).query)
        print "Returning res: " + form + res
        self.wfile.write(form + res)
        return


httpd = BaseHTTPServer.HTTPServer(('', 8080), ServerHandler)
httpd.serve_forever()
Esempio n. 29
0
    def handle_file(self, full_path):
        try:
            with open(full_path, 'rb') as reader:
                content = reader.read()
            self.send_content(content)
        except IOError as msg:
            msg = "'{0}' cannot be read: {1}".format(self.path, msg)
            self.handle_error(msg)

    # Handle unknown objects.
    def handle_error(self, msg):
        content = self.Error_Page.format(
            path=self.path, msg=msg)  # path is extracted from IP/path
        self.send_content(content, 404)

    # Send actual content.
    def send_content(self, content, status=200):
        self.send_response(status)
        self.send_header("Content-type", "text/html")
        self.send_header("Content-Length", str(len(content)))
        self.end_headers()
        self.wfile.write(content)


#-------------------------------------------------------------------------------

if __name__ == '__main__':
    serverAddress = ('', 8080)
    server = BaseHTTPServer.HTTPServer(serverAddress, RequestHandler)
    server.serve_forever()
Esempio n. 30
0
def run():
    server = BaseHTTPServer.HTTPServer((HOST_IP, PORT), MyHandler)
    #	server.socket = ssl.wrap_socket(server.socket, certfile='server.pem', server_side=True)
    server.serve_forever()