pythonbasehttpserver

Python BaseHTTPServer, how to redirect multiple hosts to ip/port?


I currently have the following code:

from BaseHTTPServer import BaseHTTPRequestHandler
from pathlib import Path
from random import randint

import json
import random

example = 'logs/example.json'

class GetHandler(BaseHTTPRequestHandler):

    # Slurp data from file
    def dummy_data(self):
        json_result = Path(example)

        if json_result.is_file():
            return json.load(open(example))

    # Return data or empty
    def random_selection(self):
        data = self.dummy_data()

        try:
            return random.sample(data, randint(1, len(data)+50))
        # Purposefully introduce entropy
        except ValueError:
            return ''

    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()

        self.wfile.write(json.dumps(self.random_selection()))
        return

if __name__ == '__main__':
    from BaseHTTPServer import HTTPServer
    server = HTTPServer(('localhost', 8080), GetHandler)
    print 'Starting server at http://127.0.0.1:8080'


server.serve_forever()

I have patched /etc/hosts as follows:

server-0001 server-0002 server-0003 server-0004 127.0.0.1

I am looking for a way for servers 0001-4 to redirect to 127.0.0.1:8080 but am not seeing how? Is this something to do with /etc/resolv.conf? I am using OSX but hopefully any *nix solution should work I'm hoping (unless ipfw evidently, since we no longer have it like sane people).


Solution

  • Looks like the sanest answer was to patch /etc/hosts, then change port of BaseHTTPServer to 80. This does not solve the origional question but is a fair compromise.

    Patching Script:

    #!/bin/bash
    
    # ensure running as root
    if [ "$(id -u)" != "0" ] ; then
      exec sudo "$0" "$@"
    fi
    
    
    if ! grep "^#- marker " /etc/hosts ; then
      echo -e '\n##+ marker' >> /etc/hosts
      while read server ; do
        [ 'x' != "${server}x" ] && echo -e "127.0.0.1 ${server}.io www.${server}.io" >> /etc/hosts
      done <read/servers.txt
      echo -e '\n##- marker' >> /etc/hosts
    fi
    

    Modification to Python

    ....
    def main():
        try:
            server = HTTPServer(('', 80), GetHandler)
            print '->> Starting server at http://127.0.0.1:80 and all patched hosts'
            server.serve_forever()
        except KeyboardInterrupt:
            print '->> Interrupt received; closing server socket'
            server.socket.close()
    
    if __name__ == '__main__':
        main()