viernes, 15 de marzo de 2013

[Solution] Removing the Server-Tag from your homemade python's web server

( applies to BasicHTTPServer / SimpleHTTPServer / CGIHTTPServer )
Sometimes when you're playing to be a ninja in python and you got the crazy and sticky idea of build your own web server just for pass the time ;-). You may find some tricky things in the fly, things that maybe you would like to change like the “Server-tag” of your homemade python's web server :-) (that in my case says that is “Server: SimpleHTTP/0.6 Python/2.7.3”) so if you're stuck with that, here i pasted my python's script and leave my solution, i hope and it could be useful to you. :)
#!/usr/bin/env python

import SocketServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

class http_handler(SimpleHTTPRequestHandler):
    def send_response(self, code, message=None):
        this is a copy-and-pase of the function send_response method in
        '/usr/lib/python2.7/' file.
        in the code below i just edited the line
        "self.send_header('Server', self.version_string())"
        for my own to remove the Server-Tag in the Header. ;-)
        if message is None:
            if code in self.responses:
                message = self.responses[code][0]
                message = ''
        if self.request_version != 'HTTP/0.9':
            self.wfile.write("%s %d %s\r\n" %
                                (self.protocol_version, code, message))
            # print (self.protocol_version, code, message)
        self.send_header('Server', "jimmy's python web server") # <= this line was edited 'cause i didn't
                                                                #    like the default Server-Tag in the Header
        self.send_header('Date', self.date_time_string())

server_addr = ('',8000)
httpd = SocketServer.TCPServer(server_addr, http_handler)
My solution:
you must to override the send_response method (i copied it and pasted it all that code from it sources in /usr/lib/python2.7/, so don't be scary ;) ) and overrode this line
self.send_header('Server', self.version_string())
with my own putting attention to the syntax. so This is my new line
self.send_header('Server', "jimmy's python web server")
if you have a linux distro, you can use the curl command to verify the changes when your server been running with this command in your linux terminal:
curl -v localhost:8000
and that's it!, hope to help. Feel free to left commentaries, doubts or corrections :)
see ya'!

No hay comentarios: