我正在尝试创建一个运行Web服务器的端口转发脚本。访问网络服务器后,它将把用户转发到在另一个端口上运行的阵列中的第一台网络服务器。
每次在浏览器中进行刷新时,页面都需要根据将用户重定向到的Web服务器进行更改。网络服务器上的每个页面都有另一种颜色,以便我可以查看服务器是否将我重定向到正确的页面。
不幸的是,对于当前代码,它不起作用。端口会更改,这很好,但是页面内容不会更改。
代码如下:
import socketimport threadingimport sysimport timedef handle(buffer): return bufferdef transfer(src,dst,direction): src_name = src.getsockname() src_address = src_name[0] src_port = src_name[1] dst_name = dst.getsockname() dst_address = dst_name[0] dst_port = dst_name[1] buffer = ' ' while buffer: buffer = src.recv(1024) if buffer: if direction: print("[+] %s:%d >>> %s:%d [%d]" % (src_address,src_port,dst_address,dst_port,len(buffer))) else: print("[+] %s:%d <<<%s:%d [%d]" % (dst_address,src_address,len(buffer))) dst.sendall(buffer) else: break;def server(local_host,local_port,remote_host,remote_port,max_connection): server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) server_socket.bind((local_host,local_port)) server_socket.listen(5) server_queue = [9999,8888,7777] # connect with first port in array new_remote_port = server_queue[0] cOnnected= True while True: try: new_remote_port = server_queue[0] # connect to remote server try: local_socket,local_address = server_socket.accept() remote_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) print('[+] Server started [%s:%d]' % (local_host,local_port)) print('[+] Connect to [%s:%d] to get the content of [%s:%d]' % (local_host,new_remote_port)) remote_socket.connect((remote_host,new_remote_port)) except socket.error: cOnnected= False remote_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) print("Connection lost... reconnecting") while not connected: try: remote_socket.connect((remote_host,new_remote_port)) cOnnected= True print("Re-connection succesful") except socket.error: time.sleep(2) else: print("Starting threads!!") s = threading._start_new_thread(transfer,(remote_socket,local_socket,False)) r = threading._start_new_thread(transfer,(local_socket,remote_socket,True)) except socket.error: cOnnected= False remote_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM) print("Connection lost... reconnecting") while not connected: try: remote_socket.connect((remote_host,new_remote_port)) cOnnected= True print("Re-connection succesful") except socket.error: time.sleep(2) else: # on success last_used_port = server_queue.pop(0) # pop left print("Last used port: " + str(last_used_port)) server_queue.append(last_used_port) # append to end of array print("[+] Connection setup succesful")def main(): if len(sys.argv) != 5: print("Usage : ") print("\tpython %s [L_HOST] [L_PORT] [R_HOST] [R_PORT]" % (sys.argv[0])) print("Example : ") print("\tpython %s 127.0.0.1 8888 127.0.0.1 22" % (sys.argv[0])) print("Author : ") print("\tWangYihang ") exit(1) LOCAL_HOST = sys.argv[1] LOCAL_PORT = int(sys.argv[2]) REMOTE_HOST = sys.argv[3] REMOTE_PORT = int(sys.argv[4]) MAX_COnNECTION= 0x10 server(LOCAL_HOST,LOCAL_PORT,REMOTE_HOST,REMOTE_PORT,MAX_CONNECTION)if __name__ == "__main__": main()
Web服务器代码
import http.serverimport socketserverPORT = 8888Handler = http.server.SimpleHTTPRequestHandlerwith socketserver.TCPServer(("",PORT),Handler) as httpd: print("serving at port",PORT) httpd.serve_forever()
这是我为测试您的代码而编写的一台小服务器:
import contextlibimport selectimport textwrapfrom http.server import BaseHTTPRequestHandlerfrom socketserver import TCPServer,ThreadingMixInSERVERS = [ (7777,'red'),(8888,'green'),(9999,'blue')]class ThreadedTCPServer(ThreadingMixIn,TCPServer): # Don't join on threads before exiting daemon_threads = Trueclass ColorHandler(BaseHTTPRequestHandler): """HTTP request handler that just generates different colored pages.""" def do_GET(self): if self.path != '/': self.send_error(404) return self.send_response(200) self.send_header('Content-Type','text/html') self.send_header('Cache-Control','no-cache') self.end_headers() color = getattr(self.server,'color','white') self.wfile.write(textwrap.dedent(f"""\ """).encode('utf-8'))if __name__ == '__main__': servers = [] with contextlib.ExitStack() as stack: for port,color in SERVERS: server = ThreadedTCPServer(('',port),ColorHandler) server.color = color servers.append(stack.enter_context(server)) # select loop while True: try: read,write,err = select.select(servers,[],[]) except KeyboardInterrupt: break for server in read: server.handle_request()
它似乎可以与Chrome一起使用。但是,我认为您的代码仍然存在问题,那就是您的transfer线程将在每次请求后在src.recv上阻塞。因此,当本地连接终止时,您现在需要重新编写代码以关闭与转发端口的连接。
【转自:外国服务器 http://www.558idc.com/shsgf.html转载请说明出处】