def cli(bwport, port, listen, basedir): Handler = RequestHandler Handler.bwport = bwport Handler.basedir = basedir ForkingTCPServer.allow_reuse_address = True with ForkingTCPServer((listen, port), Handler) as httpd: httpd.serve_forever()
def tcprpcserver(host,port, max_children, timeout, poll_interval, forking, daemon_threads, dispatcher): if forking: tcprpcserver = ForkingTCPServer(server_address = (host,port), RequestHandlerClass = RPCStreamRequestHandler) mode = _('Forking') else: tcprpcserver = ThreadingTCPServer(server_address = (host,port), RequestHandlerClass = RPCStreamRequestHandler) tcprpcserver.daemon_threads = daemon_threads mode = _('Threading') tcprpcserver.serializer = Packer() tcprpcserver._dispatcher = dispatcher tcprpcserver.max_children = max_children tcprpcserver.timeout = timeout _logger = logging.getLogger("listener.tcprpcserver") _logger.info(_("service tcprpc running on %s port %s in mode %s") % (host, port, mode)) tcprpcserver.serve_forever(poll_interval = poll_interval)
from socketserver import ForkingTCPServer, BaseRequestHandler class MyHandler(BaseRequestHandler): def handle(self): print(f"[来自{self.client_address}的消息:]\n") data = self.request.recv(2048) if data: print(data.decode("utf-8")) self.request.send( "HTTP/1.1 200 ok\r\n\r\n<h1>TCP Server Forking</h1>".encode( "utf-8")) if __name__ == "__main__": with ForkingTCPServer(('', 8080), MyHandler) as server: server.serve_forever()
enc("Oh hi there, I didn't see you come in!\n" " How do you do?\n" " There must be a flag lying around somewhere on this blech.\n" " If you could be so kind and help me find it.\n" " How do 15 seconds of RCE in IPython sound?\n" " Sadly the cat ate some of characters while I baked them. 🐈\n\n") ) while True: userinput = cat_food(decode(f_in.readline())).strip() if userinput.startswith("%"): f_out.write( enc(( "Out[?]: The cat 🐈 will eat lines starting with `%`.\n" " Oh and btw I found out it eats the following: `{}` \n\n" "In [.]: ".format(r)))) f_out.flush() elif "%%" in userinput: f_out.write( enc(( "Out[!]: The cat got this one. Seems to be yummy.\n\nIn [.]: " ))) else: # forward "sanitized" input to IPython si.write("{}\n".format(userinput).encode()) si.flush() if __name__ == "__main__": print("Listening on port {}".format(PORT)) ForkingTCPServer(("0.0.0.0", PORT), RequestHandler).serve_forever()
# print("sock writeable, sending " + str(len(data))) if sock.sendall(data) == 0: return data = None if writable_sock == self.wfile and received is not None: # print("wfile writeable, sending " + str(len(received))) if self.wfile.write(received) == 0: return received = None for readable_sock in readable: if readable_sock == self.rfile and data is None: data = self.rfile.read(1024) # print("rfile readable, read " + str(len(data))) if len(data) == 0: return if readable_sock == sock and received is None: received = sock.recv(1024) # print("sock readable, read " + str(len(received))) if len(received) == 0: return finally: print("closing socket" + str(sock)) sock.close() if __name__ == '__main__': # Create server and bind to set ip myserver = ForkingTCPServer((BIND_HOST, BIND_PORT), SockHandler) # activate the server until it is interrupted with ctrl+c myserver.serve_forever()
#!/usr/bin/python3 from socketserver import BaseRequestHandler, TCPServer from socketserver import ForkingTCPServer, ThreadingTCPServer class EchoHandler(BaseRequestHandler): def handle(self): print("got connection from", self.client_address) while True: data = self.request.recv(4096) print('receive', data.decode()) if data: sent = self.request.send(data) else: print("disconnect", self.client_address) self.request.close() break if __name__ == "__main__": listen_address = ("0.0.0.0", 9981) #server =TCPServer(listen_address, EchoHandler) server = ForkingTCPServer(listen_address, EchoHandler) server.serve_forever()
msg = self.request.recv(8192) if msg in ['exit', 'quit', '\x04']: break if not msg: break print(time.strftime('%Y-%m-%d %H:%M:%S'), self.client_address, msg) self.request.send(msg) def finish(self): self.request.send("bye\n") print(time.strftime('%Y-%m-%d %H:%M:%S'), 'Disconnect from', self.client_address) if __name__ == '__main__': port = 20000 ForkingTCPServer.allow_reuse_address = False if os.name == 'posix': serv = ForkingTCPServer(('', port), PlainTextEchoHandler) elif os.name == 'nt': serv = ThreadingTCPServer(('', port), PlainTextEchoHandler) else: raise OSError("system is not supported.") serv.allow_reuse_address = True serv.max_children = 2000 print( time.strftime('%Y-%m-%d %H:%M:%S'), "port {port} is listened, try with 'telnet localhost {port}'".format(port=port) ) serv.serve_forever()
def __init__(self, host, port, handler=RecordStreamHandler): ForkingTCPServer.__init__(self, (host, port), handler) self.stop = 0 self.timeout = 1
def test_threading_tcp_server(): # 同时处理多个客户端请求,默认无上限, 很容易遭受饱和攻击 # serv = ThreadingTCPServer(('',20000),EchoHandler) serv = ForkingTCPServer(('', 20000), EchoHandler) serv.serve_forever()
from socketserver import ForkingTCPServer from socketserver import StreamRequestHandler class Handler(StreamRequestHandler): def handle(self): request = self.rfile.read(1024) print(request.decode()) http_response = b"""\ HTTP/1.1 200 OK Hello, World! """ self.wfile.write(http_response) server = ForkingTCPServer(("127.0.0.1", 8888), Handler) server.serve_forever()
def shutdown(self): self.stopped = True ForkingTCPServer.shutdown(self)
fcontent = open(storagedir + x + '.content', 'rb') self.send_response(200) headerstr = fhead.read() headermap = eval(headerstr) for key, value in headermap.items(): if key != 'Date': self.send_header(key, value) self.end_headers() while True: chunk = fcontent.read(chunksize) if chunk: self.wfile.write(hex(len(chunk))[2:].encode('utf-8')) self.wfile.write('\r\n'.encode('utf-8')) self.wfile.write(chunk) self.wfile.write('\r\n'.encode('utf-8')) else: self.wfile.write(hex(0)[2:].encode('utf-8')) self.wfile.write('\r\n'.encode('utf-8')) self.wfile.write('\r\n'.encode('utf-8')) break fcontent.close() fhead.close() if not os.path.exists(storagedir): os.makedirs(storagedir) httpd = ForkingTCPServer(('', port), Proxy) print('start my proxy at', port) httpd.serve_forever()
def server_bind(self): if isinstance(ip.ip_address(self.server_address[0]), ip.IPv6Address): self.socket = socket.socket(socket.AF_INET6, self.socket_type) ForkingTCPServer.server_bind(self)
#if archivo.find("ppm") != -1: # archivo = '/home/lucas/compu2/lab/tps/tp3/aviso.html' # extension = 'html' # fd = os.open(archivo, os.O_RDONLY) # body = os.read(fd, os.path.getsize(archivo)) # os.close(fd) # header = bytearray("HTTP/1.1 404 Not Found\r\nContent-type:"+ dic[extension] +"\r\nContent-length:"+str(len(body))+"\r\n\r\n",'utf8') #self.request.sendall(header) #self.request.sendall(body) except Exception as x: print(x) archivo = args.root + '404error.html' extension = 'html' fd = os.open(archivo, os.O_RDONLY) body = os.read(fd, os.path.getsize(archivo)) os.close(fd) header = bytearray("HTTP/1.1 404 Not Found\r\nContent-type:"+ dic[extension] +"\r\nContent-length:"+str(len(body))+"\r\n\r\n",'utf8') self.request.sendall(header) self.request.sendall(body) with ForkingTCPServer(('0.0.0.0', args.port[0]), Handler) as server: server.allow_reuse_address = True server.serve_forever()
def finish(self): self.request.send("bye\n") print(time.strftime('%Y-%m-%d %H:%M:%S'), 'Disconnect from', self.client_address) if __name__ == '__main__': if len(sys.argv) == 2: port = int(sys.argv[1]) if sys.argv[1].isdigit() else 20000 else: port = 20000 serv = None ForkingTCPServer.allow_reuse_address = False if os.name == 'posix': serv = ForkingTCPServer( ('', port), PlainTextEchoHandler) # socket.error can be raised elif os.name == 'nt': serv = ThreadingTCPServer( ('', port), PlainTextEchoHandler) # socket.error can be raised else: raise OSError("system is not supported.") if serv is not None: serv.allow_reuse_address = True serv.max_children = 2000 print( time.strftime('%Y-%m-%d %H:%M:%S'), "Port {port} is listened, try with 'telnet localhost {port}'". format(port=port)) try: serv.serve_forever()
from socketserver import ForkingTCPServer, StreamRequestHandler, ForkingMixIn from controllers import * class MessageHandler(StreamRequestHandler): def handle(self): self.writeString( "GreyH@t Stepping into Security - Lab Server\n" + "v1.3\n" + "------------------\n" + "Available commands: [l[ogin], r[egister], i[nfo], h[elp], c[lear], q[uit]]\n" ) while True: last_command = mainmenu.MainMenu().handle(self) if last_command == "quit" or last_command == 'q': return if last_command == "logout": self.writeString("Ok. You are now logged out.\n") def writeString(self, string): self.wfile.write(bytes(string, "utf-8")) if __name__ == '__main__': server = ForkingTCPServer(("0.0.0.0", 1000), RequestHandlerClass=MessageHandler, bind_and_activate=False) server.allow_reuse_address = True server.server_bind() server.server_activate() print("Now listening on port 1000!") server.serve_forever()
def run(self): serv = ForkingTCPServer(('', self.port), self.handle) self.log.info('start server on port {}'.format(self.port)) serv.serve_forever()
from socketserver import BaseRequestHandler, TCPServer from socketserver import ForkingTCPServer, ThreadingTCPServer class EchoHandler(BaseRequestHandler): def handle(self): print("got connection from", self.client_address) while True: data = self.request.recv(4096) if data: sent = self.request.sendall(data) else: print("disconnect", self.client_address) self.request.close() break listen_address = ('', 2018) if __name__ == "__main__": server = ForkingTCPServer(listen_address, EchoHandler) server.serve_forever()