1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| from http.server import HTTPServer, BaseHTTPRequestHandler import urllib.request as urllib2 import logging import re import gzip import logging import sys from bs4 import BeautifulSoup
logger = logging.getLogger(__name__) logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
fh = logging.FileHandler(sys.path[0] + '/考试.log',mode='a', encoding='utf-8') fh.setLevel(logging.INFO) fh.setFormatter(formatter) logger.addHandler(fh)
ch = logging.StreamHandler() ch.setLevel(logging.INFO) ch.setFormatter(formatter) logger.addHandler(ch)
class ProxyHandler(BaseHTTPRequestHandler): target_host = 'kaoshi.wjx.top'
def proxy(self): header = dict(self.headers) logger.info('header: %s', header) if self.path == '/npm/eruda': self.send_response(200) self.end_headers() with open(sys.path[0] + '/eruda.js', 'r', encoding='utf-8') as f: self.wfile.write(f.read().encode('utf-8')) return elif self.path == '/script.js': self.send_response(200) self.end_headers() with open(sys.path[0] + '/script.js', 'r', encoding='utf-8') as f: self.wfile.write(f.read().encode('utf-8')) return else: header['Host'] = 'kaoshi.wjx.top' request = urllib2.Request(url='http://' + "101.37.44.53" + self.path, headers=header, method=self.command) logger.info('request: %s', request.full_url) with urllib2.urlopen(request) as f: logger.info("status: %s", f.status) logger.info("headers: %s", f.headers)
self.send_response(f.status) for (key, value) in f.headers.items(): if key == 'Content-Type': self.send_header(key, value) self.end_headers() data = f.read() if f.headers['Content-Encoding'] == 'gzip': data = gzip.decompress(data) data = data.decode('utf-8') if 'https' in data: data = data.replace('https://', 'http://') logger.info("data: %s", data) logger.info('<<<<: %s', self.path) data = get_answer(data) self.wfile.write(data.encode('utf-8'))
def do_GET(self): self.proxy()
def do_POST(self): self.proxy()
def get_answer(data: str): if '</body>' in data: i = data.index('</body>') script = ''' <script src="//kaoshi.wjx.top/npm/eruda"></script><script>setTimeout(() => eruda.init(), 3000);</script> ''' script = script + '''<script src="//kaoshi.wjx.top/script.js"></script>''' data = data[:i] + script + data[i:] return data
def run(): server_address = ('', 80) httpd = HTTPServer(server_address, ProxyHandler) httpd.serve_forever()
if __name__ == '__main__': run()
|