def serve_forever(self, poll_interval=0.5): self._BaseServer__is_shut_down.clear() try: while not self._BaseServer__shutdown_request: r, w, e = SocketServer._eintr_retry( select.select, [self], [], [], poll_interval) if self in r: self._handle_request_noblock() self.serve_cleanup() finally: self._BaseServer__shutdown_request = False self._BaseServer__is_shut_down.set()
#This is expected to happen often! #There is an opportunity to see more samples #of the offending traffic hit the firewall #before the Aclizer script kicks off and denys the traffic #on the edge(every 5 mins polling the banlist.txt) if CheckBanList(i) == 1: #Remember, this is expected, and just means you already #have logged a sample of the traffic, and it's in the banlist print "External IP: " + str(i) + " Already Banned" #Otherwise, ban the traffic, and log the raw packet #as a sample of the offending traffic. elif CheckBanList(i) == 0: AddIP(i) LogPacket(data) print "External IP: " + str(i) + " Banned" if __name__ == "__main__": #Specify the local IP Address if nessecary, and #port number to listen for inbound syslog messages. HOST, PORT = "localhost", 11514 #Start your engines! server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler) #Don't stop! server.serve_forever() __author__ = 'JAB'
# https://gist.github.com/omz/4051823 import SimpleHTTPServer import SocketServer import webbrowser import os os.chdir('/') Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", 0), Handler) port = httpd.server_address[1] webbrowser.open('http://localhost:' + str(port), stop_when_done=True) httpd.serve_forever()
print('connected from:', self.client_address) while True: fileinfo_size = struct.calcsize('128sI') self.buf = self.request.recv(fileinfo_size) if self.buf: self.filename, self.filesize = struct.unpack('128sI', self.buf) print 'filesize is:', self.filesize, 'filename size is :', len( self.filename) self.filenewname = os.path.join( "/code", ('new_' + self.filename).strip('\00')) print self.filenewname, type(self.filenewname) recvd_size = 0 file = open(self.filenewname, 'wb') print 'stat receiving...' while not recvd_size == self.filesize: if self.filesize - recvd_size > 1024: rdata = self.request.recv(1024) recvd_size += len(rdata) else: rdata = self.request.recv(self.filesize - recvd_size) recvd_size = self.filesize file.write(rdata) file.close() print 'receive done' self.request.close() tcpServ = SocketServer.ThreadingTCPServer(ADDR, MyRequestHandler) print 'waiting for connection...' tcpServ.serve_forever()
def run(self): server = SocketServer.UDPServer((socket.gethostname(), 9999), MyUDPHandler) server.serve_forever()
contents = "<html><head>\r\n" + \ "<title>404 Not Found</title>\r\n" + \ "</head><body>\r\n" + \ "<h1>Nothing matches the given URI</h1>\r\n" + \ "</body></html>" self.respond(status, mime_type, contents) def handle_302(self,path): status = "302 Found" mime_type = "html" contents = "<HTML><HEAD>\r\n" + \ "<TITLE>302 Moved</TITLE></HEAD><BODY>\r\n" + \ "<H1>302 Moved</H1>\r\n" + \ "The document has moved\r\n" + \ "<A HREF=" + path + "/index.html>here</A>.\r\n" + \ "</BODY></HTML>" location = "Location: " + path + "/index.html" self.respond(status, mime_type, contents) self.request.sendall(location) if __name__ == "__main__": HOST, PORT = "localhost", 8080 SocketServer.TCPServer.allow_reuse_address = True # Create the server, binding to localhost on port 8080 server = SocketServer.TCPServer((HOST, PORT), MyWebServer) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever()
import os import webservers.CustomHTTPServer import KarrigellRequestHandler import k_config import k_utils class RequestHandler(KarrigellRequestHandler.KarrigellRequestHandler, webservers.CustomHTTPServer.RequestHandler): pass if k_config.silent: import sys sys.stdout = k_utils.silent() sys.stderr = k_utils.silent() if k_config.debug: print "Debug level %s" %k_config.debug # Launch the server import SocketServer server=SocketServer.TCPServer(('', k_config.port), RequestHandler) print "Karrigell %s running on port %s" \ %(KarrigellRequestHandler.__version__,k_config.port) print "Press Ctrl+C to stop" try: server.serve_forever() except KeyboardInterrupt: k_utils.trace("Ctrl+C pressed. Shutting down.")
def main(): socket3 = SocketServer('Castlebots3', 8080) mic3 = Microphone() socket3.connectSocket() mic3.read() mic3.getTime()
def run(self): print 'PacketServer: Starting up server' skt_server = SocketServer.TCPServer((self.ip, self.port), PacketClientHandler) skt_server.serve_forever()
class MytcpHandler(SocketServer.BaseRequestHandler): def handle(self): address = self.client_address[0].strip() all_data = "" while 1: if address not in ['127.0.0.1']: self.request.sendall("Error:Server rejected the connection.\n") break data = self.request.recv(1024).strip() if not data: break all_data = all_data + data if len(all_data) != 0: if handle_data.handle(all_data.strip()): self.request.sendall("Message is invalid") #self.client_address[0] if __name__ == "__main__": log.log('Server runing...') try: server = SocketServer.ThreadingTCPServer((HOST, PORT), MytcpHandler) server.serve_forever() except KeyboardInterrupt: print sys.exit(0) except Exception, e: print e sys.exit(-1)
print "Connection from: ", self.client_address # This creates a variable with some data in it so the while loop will execute initially data = 'anyData' # While there is a length to data execute the body while len(data): # Data is set to the .request.recv() method which is basically what the server will rec. from a client connection data = self.request.recv(1024) print "Client sent the following: \n", data # Here we use the request.send() method to send data to the client # This could be anything, so if you are analyzing malware you could change this to send back what the malware asked for # It's possible you may learn more about the malware's behavior this way self.request.send(data) # This executes outside the body of the while loop, which only means the connection is closed print "Connection closed" # Here we setup a variable which will contain a tuple of the IP ("0.0.0.0" means listen on all addresses) # and it takes in an argument from the CLI for the port serverAddr = ("0.0.0.0", int(sys.argv[1])) print "Server started, waiting for a connection...." # Tells the SocketServer to invoke the TCPServer() method - this takes two arguments # 1st argument is a tuple which contains the IP/Port information, which we made with serverAddr variable # The second argument is a Class which will be used to handle connections to the server. # This was the class we created earlier in the code server = SocketServer.TCPServer(serverAddr, EchoHandler) # This is added to have the TCPServer process as many clients as possible # You could use another method to handle single connections, but that is really never used server.serve_forever()
def __init__(self, host, port, root_dir): os.chdir(root_dir) handler = SimpleHTTPServer.SimpleHTTPRequestHandler self.server = SocketServer.TCPServer((host, int(port)), handler, False) self.server.allow_reuse_address = True
conn.send(returnCommand) return def handle(self): self.business = { '0': self.logDetach, '1': self.login, '2': self.info, '3': self.chat, '4': self.handlePoll, '5': self.FilesUpload, '6': self.FilesDownload, '7': self.fileInfo, "8": self.clientDetach, "9": self.dbRegister, "10": self.userUpdate, "11": self.photomessage, "12": self.askImage } print '...connected from:' + self.client_address[0] Flag = True conn = self.request while Flag: cmd = self.Command() if cmd == 8 or cmd == 0: break server = SocketServer.ThreadingTCPServer(('0.0.0.0', 14333), MyServer) server.serve_forever()
def handle(self): # self.request is the TCP socket connected to the client print "[*] Received FTP-Data Request" print "[*] Sending Empty List" # just send back the same data, but upper-cased self.request.sendall("total 0\r\n\r\n") self.request.close() if __name__ == "__main__": HOST, PORT = ip, 8000 SocketServer.TCPServer.allow_reuse_address = True print "[*] Starting the HTTP Server." # Create the server, binding to localhost on port 8000 HTTPServer = SocketServer.TCPServer((HOST, PORT), HTTPHandler) # Running the http server (using a thread so we can continue and listen for FTP and FTP-Data). HTTPThread = threading.Thread(target=HTTPServer.serve_forever) HTTPThread.daemon = True HTTPThread.start() print "[*] Starting the FTP Server." # Running the FTP server. FTPServer = SocketServer.TCPServer((HOST, 21), FTPHandler) # Running the FTP server thread. FTPThread = threading.Thread(target=FTPServer.serve_forever) FTPThread.daemon = True FTPThread.start()
__author__ = 'VanDuan' import SocketServer from SocketServer import ThreadingTCPServer import sys host = SocketServer.gethostname() port = sys.argv[1:] #get port from commandline port.reverse() port = int(''.join(port)) #convert to integer #print port server = ThreadingTCPServer((''))
from __future__ import print_function try: import SimpleHTTPServer as srvmod except ImportError: import http.server as srvmod # NOQA try: import SocketServer as socketserver except ImportError: import socketserver # NOQA PORT = 8000 Handler = srvmod.SimpleHTTPRequestHandler httpd = socketserver.TCPServer(("", PORT), Handler) print("serving at port", PORT) httpd.serve_forever()
def main(): socket4 = SocketServer('Castlebots4', 8080) mic4 = Microphone() socket4.connectSocket() mic4.read() mic4.getTime()
self.request.sendall("OK\n".encode('utf-8')) return (True) self.request.sendall("ERR\n".encode('utf-8')) return (False) # API用スレッド def api_server_th(): api_server.serve_forever() # API起動 try: piradio_api_port api_server = SocketServer.ThreadingTCPServer( ("localhost", piradio_api_port), APIHandler) apit = threading.Thread(target=api_server_th) apit.start() except: pass # APIからの再生処理 def api_p_start(): global p_selected global p_last_selected global stop_play_cmd # 再生開始のWAITの表示 try: use_gui popup_text('WAIT', (255, 174, 0))
observable.register_observer(observer) while True: time.sleep(1) except Exception as e: logging.warning('Removed streaming client %s: %s', self.client_address, str(e)) else: self.send_error(404) self.end_headers() if __name__ == "__main__": socket_server = SocketServer((SOCKET_SERVER_HOST, SOCKET_SERVER_PORT), SocketServerRequestHandler) print 'Starting socket server on port ', SOCKET_SERVER_PORT socket_server_thread = threading.Thread(target=socket_server.serve_forever) socket_server_thread.daemon = True socket_server_thread.start() http_server = BaseHTTPServer.HTTPServer((HTTP_SERVER_HOST, HTTP_SERVER_PORT), HttpRequestHandler) print 'Starting http server on port ', HTTP_SERVER_PORT http_server_thread = threading.Thread(target=http_server.serve_forever) http_server_thread.daemon = True http_server_thread.start()
server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(username, password) server.sendmail(FROM, [TO], message) server.quit() SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) def do_POST(self): FROM = "*****@*****.**" TO = "*****@*****.**" message = ms username = "******" password = "******" server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(username, password) server.sendmail(FROM, [TO], message) server.quit() Handler = MyHandler httpd = SocketServer.TCPServer(("", os.getenv(PORT, 8080)), Handler) print "serving at port", PORT httpd.serve_forever()
import SimpleHTTPServer import SocketServer PORT = 8000 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler Handler.extensions_map.update({ '.webapp': 'application/x-web-app-manifest+json', }) httpd = SocketServer.TCPServer(("192.168.1.43", PORT), Handler) #aqui va la direccion local, con el comando ifconfig la saca, 192.168.1.43:8000 print "Serving at port", PORT httpd.serve_forever()
import SocketServer class UDPEchoHandler(SocketServer.BaseRequestHandler): def handle(self): client_address = self.client_address client_data, sock = self.request print 'Got : ' + client_data + ' from ' + str(client_address) sock.sendto(client_data.upper(), client_address) server_address = ('127.0.0.1', 33333) udp_echo_server = SocketServer.UDPServer(server_address, UDPEchoHandler) udp_echo_server.serve_forever()
nohup='' self.cmd("echo > ../nohup.out ") x=0 for i in cmd: j=' "%d":"%s",' %(x,i) nohup+= j x+=1 nohup='{%s}'%nohup[:len(nohup)-1] cmd_h=self.cmd("cat /var/lib/dhcp/dhcpd.leases|grep host|awk '{print$2}' ").replace('"','').split('\n') x=0 dhcp='' for i in cmd_h: j=' "%d":"%s",' %(x,i) dhcp+= j x+=1 dhcp='{%s}'%dhcp[:len(dhcp)-1] open('d.json','w').write(dhcp) open('o.json','w').write(nohup) print dhcp,nohup print "reading .." sleep(5) back().start() PORT = 8009 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever()
def start(self, callback, port): self.httpd = SocketServer.ThreadingTCPServer(('', port), Proxy) self.httpd.temp = self.temp threading.Thread(target=self.httpd.serve_forever).start() gobject.idle_add(callback, 'http://localhost:' + str(port))
def process(): HOST, PORT = "10.0.0.42", 8080 server = SocketServer.TCPServer((HOST, PORT), PiBrainServer) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever()
def __init__(self): self.server = SocketServer.TCPServer((self.HOST, self.PORT), TcpHandler)
# Display web refresh info only if setting is turned on f.write('</b></p>') length = f.tell() f.seek(0) self.send_response(200) encoding = sys.getfilesystemencoding() self.send_header("Content-type", "text/html; charset=%s" % encoding) self.send_header("Content-Length", str(length)) self.end_headers() return f # Start Web Server Processing os.chdir(web_server_root) SocketServer.TCPServer.allow_reuse_address = True httpd = SocketServer.TCPServer(("", web_server_port), DirectoryHandler) print("----------------------------------------------------------------") print("%s %s" % (PROG_NAME, PROG_VER)) print("---------------------------- Settings --------------------------") print("Server - web_page_title = %s" % web_page_title) print(" web_server_root = %s/%s" % (BASE_DIR, web_server_root)) print(" web_server_port = %i " % web_server_port) print("Content - web_image_height = %s px (height of content)" % web_image_height) print(" web_iframe_width = %s web_iframe_height = %s" % (web_iframe_width, web_iframe_height)) print(" web_iframe_width_usage = %s (of avail screen)" % (web_iframe_width_usage)) print(" web_page_refresh_sec = %s (default=180 sec)" % web_page_refresh_sec) print(
#!/usr/bin/env python import SimpleHTTPServer import SocketServer import os class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): if self.path.startswith("/status"): with open("/tmp/current-volume.new", "w") as f: f.write(self.path[8:]) os.rename("/tmp/current-volume.new", "/tmp/current-volume") self.path = "/" return SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self) SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer(("0.0.0.0", 8000), MyRequestHandler) server.serve_forever()
def examSimpleHTTP(self): PORT = 8000 Handler = SimpleHTTPServer.SimpleHTTPRequestHandler httpd = SocketServer.TCPServer(("", PORT), Handler) print "serving at port", PORT httpd.serve_forever()
print("url: %s" % (url, )) response = requests.put(url, data=self.data_string, headers=self.headers, stream=True) if response.status_code == 200: self._write_cache(cached_file_folder, cached_file_header, cached_file_content, response) else: print('Error when requesting file :') print('Requested url : %s' % (url, )) print('Status code : %s' % (response.status_code, )) print('Content : %s' % (response.content, )) self.send_response(response.status_code) return response.content else: print("Request for data present in cache: %s" % (cached_file_folder, )) self._send_content(cached_file_header, cached_file_content) # Main code that start the HTTP server httpd = SocketServer.ForkingTCPServer(('', PORT), Proxy) httpd.allow_reuse_address = True print "Listening on port " + str( PORT) + "(Press Ctrl+C/Ctrl+Z to stop HTTPD Caching script)" print "Caching folder " + CACHE_ROOT + ", Tmp folder for generated files " + TMP_ROOT signal.signal(signal.SIGINT, signal_handler) httpd.serve_forever()
Based on code from http://effbot.org/librarybook/simplehttpserver.htm ''' import SocketServer import SimpleHTTPServer import urllib PORT = 8080 class Proxy(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(self): # Is this a special request to redirect? prefix = '/api2' if self.path.startswith(prefix): # Strip off the pefix. newPath = "http://www.quehambre.cl" + self.path print newPath else: # Concatenate the curr dir with the relative path. newPath = self.translate_path(self.path) self.copyfile(urllib.urlopen(newPath), self.wfile) SocketServer.ThreadingTCPServer.allow_reuse_address = True httpd = SocketServer.ThreadingTCPServer(('', PORT), Proxy) print "serving at port", PORT httpd.serve_forever()
def do_GET(self): global revolutions global frequency global distance global velocity data = { "revolutions": revolutions, "frequency": frequency, "distance": distance, "velocity": velocity, } self.send_response(200) self.send_header('Content-type', 'application/json') self.send_header('Access-Control-Allow-Origin', '*'), self.send_header('Access-Control-Allow-Credentials', 'true'), self.send_header('Access-Control-Allow-Headers', 'Authorization') self.end_headers() json.dump(data, self.wfile) httpd = SocketServer.TCPServer(("", 8082), BikeRequestHandler) threading.Thread(target=sampling_thread).start() sys.stderr.write("Sampling ...\n") sys.stderr.write("Serving ...\n") httpd.serve_forever()
def main(): socket2 = SocketServer('Castlebots2', 8080) mic2 = Microphone() socket2.connectSocket() mic2.read() mic2.getTime()
# 如何支持异步和多线程:处理多个请求的服务端(客户端不用变) import SocketServer class MyServer(SocketServer.BaseRequestHandler): # 继承了BaseRequestHandler类 def setup(self): pass def handle(self): # 定义handle方法 print self.request, self.client_address, self.server conn = self.request conn.send('hello') # 给客户端发信息 flag = True while flag: data = conn.recv(1024) # 接收数据,最多只能拿1024字节 print data if data == 'exit': flag = False else: conn.send('OK') # 接收数据解答问题 conn.close() # def finish(self): pass if __name__ == '__main__': server = SocketServer.ThreadingTCPServer(('127.0.0.1', 9999), MyServer) # 接收两个参数(bind方法) server.serve_forever()
from hallled.async.SocketServer import SocketServer HOST = '127.0.0.1' # Symbolic name, meaning all available interfaces PORT = 12345 # Arbitrary non-privileged port s = SocketServer(HOST, PORT) s.run()
#from SocketServer import * from time import ctime #HOST = '' #PORT = 21567 #ADDR = (HOST, PORT) # #class MyRequestHandler(SRH): # def handle(self): # print '...connected from:', self.client_address # self.wfile.write('[%s] %s' % (ctime(), self.rfile.readline())) # tcpServ = TCP(ADDR, MyRequestHandler) # print 'waiting for connection...' # tcpServ.serve_forever() class MyRequestHandler(SocketServer.StreamRequestHandler): '''在 BaseRequest 类中,这个函数什么也不做: def handle(self): pass 在有客户消息进来的时候,handle()函数就会被调用。''' def handle(self): print '...connected from:', self.client_address[0] self.wfile.write('[%s] %s' % (ctime(), self.rfile.readline())) if __name__ == "__main__": srv = SocketServer.TCPServer(("10.43.167.19", 8080), MyRequestHandler) print 'waiting for connection...' srv.serve_forever()
import SocketServer import living_room from time import sleep class MyTCPHandler(SocketServer.BaseRequestHandler): def handle(self): self.data = self.request.recv(1024).strip() print "{} wrote:".format(self.client_address[0]) print self.data if self.data == "Living_Room": self.request.sendall(living_room.send()) if self.data.startswith("{"): living_room.rec(self.data) print "---+++---" self.request.sendall("Done") if __name__ == "__main__": HOST, PORT = "192.168.41.49", 9999 server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) server.serve_forever()
def main(): socket1 = SocketServer('Castlebots1', 8080) mic1 = Microphone() socket1.connectSocket() mic1.read() mic1.getTime()