这期内容当中小编将会给大家带来有关Python中怎么实现代理服务器,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
这里就是使用Python简单的实现一个二级代理。
#coding=utf-8 import socket import select import sys import threading import time import logging import os logsDir = "logs" if not os.path.isdir(logsDir): os.mkdir(logsDir) logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename='logs/logs.log', filemode='a') #C的IP和端口 to_addr = ('127.0.0.1', 8087) maxConnetions = 32 class Proxy: def __init__(self, addr): self.proxy = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.proxy.bind(addr) self.proxy.listen(maxConnetions) self.inputs = {self.proxy:None} self.route = {} def serve_forever(self): logging.info('proxy listen...') while 1: readable, _, _ = select.select(list(self.inputs.keys()), [], []) for self.sock in readable: if self.sock == self.proxy: self.on_join() else: try: data = self.sock.recv(8192) except Exception, e: logging.error(str(e)) self.on_quit() continue if not data: self.on_quit() else: try: self.route[self.sock].send(data) except Exception, e: logging.error(str(e)) self.on_quit() continue def on_join(self): client, addr = self.proxy.accept() logging.info("proxy client " + str(addr) + 'connect') forward = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: forward.connect(to_addr) except Exception, e: logging.error(str(e)) client.close() return self.inputs [client] = None self.inputs [forward] = None self.route[client] = forward self.route[forward] = client #删除连接 def on_quit(self): ls = [self.sock] if self.sock in self.route: ls.append(self.route[self.sock]) for s in ls: if s in self.inputs: del self.inputs[s] if s in self.route: del self.route[s] s.close() if __name__ == "__main__": try: Proxy(('', 8192)).serve_forever() except KeyboardInterrupt, e: logging.error("KeyboardInterrupt" + str(e))
上述就是小编为大家分享的Python中怎么实现代理服务器了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。