Created
February 16, 2013 06:33
-
-
Save xiaojay/4965827 to your computer and use it in GitHub Desktop.
simple proxy server for debug
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
#coding=utf-8 | |
import BaseHTTPServer, SocketServer, urllib, urllib2, urlparse, zlib, socket, os, sys, errno, base64, re, time, datetime | |
HopHeaders = ['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', 'upgrade'] | |
def print_red(s): | |
print '\033[0;31;48m%s\033[0m'%s | |
class ProxyHandler(BaseHTTPServer.BaseHTTPRequestHandler): | |
def do_GET(self): | |
print_red(self.path) | |
req = urllib2.Request(self.path) | |
for h in self.headers: | |
if h not in HopHeaders: | |
req.add_header(h, self.headers.getheader(h)) | |
print h, self.headers.getheader(h) | |
req.add_header("connection", "close") | |
try: | |
resp = urllib2.urlopen(req) | |
print 'fetched' | |
except urllib2.URLError, e: | |
print e | |
self.connection.close() | |
self.send_response(resp.getcode(), resp.msg) | |
for name, value in resp.headers.items(): | |
if name == 'connection': | |
value = 'close' | |
print name, value | |
self.send_header(name, value) | |
self.end_headers() | |
data = resp.read() | |
open('temp/%s'%urlparse.urlsplit(self.path)[1], 'w').write(data) | |
self.wfile.write(data) | |
self.connection.close() | |
if __name__ == "__main__": | |
from optparse import OptionParser | |
parser = OptionParser() | |
parser.add_option('-p', '--port', type='int', dest='port', help=u'监听端口', default=8000) | |
(options, args) = parser.parse_args() | |
print "--------------------------------------------" | |
print "Listen Addr : 0.0.0.0:%d" % listen_port | |
print "--------------------------------------------" | |
httpd = BaseHTTPServer.HTTPServer(("0.0.0.0", listen_port), ProxyHandler) | |
httpd.serve_forever() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment