Many python 50 lines of code on the Web implement a proxy server, but are prone to exceptions, resulting in exit.
The proxy server here refers to a level two proxy server. For example: A can access b,b can access C,a cannot directly access C. At this point, if you open a two-level agent in B, you can achieve a access C. The existing tools are ccproxy.
This is a simple implementation of a two-level proxy using Python.
#coding =utf-8 Import Socket Import Select Import sys import threadingimport timeimport loggingimport oslogsdir = "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 = (' 0.0.0 .0 ', 8087) class Proxy:def __init__ (self, addr): Self.proxy = Socket.socket (socket.af_inet, socket. SOCK_STREAM) self.proxy.bind (addr) Self.proxy.listen (Ten) self.inputs = [Self.proxy] Self.r Oute = {} def serve_forever (self): logging.info (' proxy listen ... ') while 1:readable, _, _ = Select.select (Self.inputs, [], []) 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 ') fo Rward = Socket.socket (socket.af_inet, socket. SOCK_STREAM) Forward.connect (to_addr) self.inputs + = [client, forward] self.route[client] = Forwar D 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.i Nputs:self.inputs.remove (s) if s in Self.route:del Self.route[s] s. Close () if __name__ = = "__main__": Try:proxy ((', 8192)). Serve_forever () except Keyboardinterru Pt:logging.error ("Keyboardinterrupt") return
Python 50 Line code implements Proxy Server (Enhanced Edition)