Python写的Socks5协议代理服务器
程序员文章站
2023-10-17 19:59:47
直接上代码:
#!/usr/bin/python
# filename s5.py
# python dynamic socks5 proxy
# u...
直接上代码:
#!/usr/bin/python # filename s5.py # python dynamic socks5 proxy # usage: python s5.py 1080 # background run: nohup python s5.py 1080 & import socket, sys, select, socketserver, struct, time class threadingtcpserver(socketserver.threadingmixin, socketserver.tcpserver): pass class socks5server(socketserver.streamrequesthandler): def handle_tcp(self, sock, remote): fdset = [sock, remote] while true: r, w, e = select.select(fdset, [], []) if sock in r: if remote.send(sock.recv(4096)) <= 0: break if remote in r: if sock.send(remote.recv(4096)) <= 0: break def handle(self): try: pass # print 'from ', self.client_address nothing to do. sock = self.connection # 1. version sock.recv(262) sock.send("\x05\x00"); # 2. request data = self.rfile.read(4) mode = ord(data[1]) addrtype = ord(data[3]) if addrtype == 1: # ipv4 addr = socket.inet_ntoa(self.rfile.read(4)) elif addrtype == 3: # domain name addr = self.rfile.read(ord(sock.recv(1)[0])) port = struct.unpack('>h', self.rfile.read(2)) reply = "\x05\x00\x00\x01" try: if mode == 1: # 1. tcp connect remote = socket.socket(socket.af_inet, socket.sock_stream) remote.connect((addr, port[0])) pass # print 'to', addr, port[0] nothing do to. else: reply = "\x05\x07\x00\x01" # command not supported local = remote.getsockname() reply += socket.inet_aton(local[0]) + struct.pack(">h", local[1]) except socket.error: # connection refused reply = '\x05\x05\x00\x01\x00\x00\x00\x00\x00\x00' sock.send(reply) # 3. transfering if reply[1] == '\x00': # success if mode == 1: # 1. tcp connect self.handle_tcp(sock, remote) except socket.error: pass #print 'error' nothing to do . except indexerror: pass def main(): filename = sys.argv[0]; if len(sys.argv)<2: print 'usage: ' + filename + ' port' sys.exit() socks_port = int(sys.argv[1]); server = threadingtcpserver(('', socks_port), socks5server) print 'bind port: %d' % socks_port + ' ok!' server.serve_forever() if __name__ == '__main__': main()
上一篇: 跟老齐学Python之眼花缭乱的运算符
下一篇: 路面循环的Flash动画的制作方法