Created
March 23, 2012 18:37
-
-
Save showell/2173618 to your computer and use it in GitHub Desktop.
fake web server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is the world's most boring and predictable web server. Its purpose in life is | |
# to facilitate testing of upstream load balancers. The web server is light, so you can | |
# deploy a bunch of them. If you hit any instance of this web server in a browser | |
# (presumably via a load balancer, then the page will always tell you who's listening.) | |
# There's also a simple back door to kill it. It doesn't serve any actual content. | |
import time | |
import sys | |
import re | |
import os | |
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer | |
class MyHandler(BaseHTTPRequestHandler): | |
def __init__(self, context, *args): | |
self.context = context | |
BaseHTTPRequestHandler.__init__(self, *args) | |
def do_GET(self): | |
port = self.context['port'] | |
start_time = self.context['start_time'] | |
host_name = self.context['host_name'] | |
self.send_response(200) | |
self.send_header('Content-type', 'text/html') | |
self.end_headers() | |
p = self.wfile.write | |
p("I am listening on port: <h3>%d</h3>" % port) | |
p("Hostname: %s<br>" % host_name) | |
p("Your path: <b>%s</b><br>" % self.path) | |
p("updated at: %s<br>" % time.asctime()) | |
time_alive = time.time() - start_time | |
p("alive for <b>%d</b> seconds<br>" % time_alive) | |
if re.search('kill', self.path): | |
p("<h1>YOU HAVE KILLED ME!!!<h2> Goodbye.<br>") | |
self.server.socket.close() | |
else: | |
p("(use /kill to kill me)") | |
def main(): | |
try: | |
port = int(sys.argv[1]) | |
context = { | |
'host_name': os.uname()[1], | |
'port': port, | |
'start_time': time.time(), | |
} | |
def handler(*args): | |
MyHandler(context, *args) | |
server = HTTPServer(('', port), handler) | |
print 'started httpserver...' | |
server.serve_forever() | |
except KeyboardInterrupt: | |
print '^C received, shutting down server' | |
server.socket.close() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment