def hostServer(name): srvr = socketserver.UDPServer((netHelper.getIP(), 4230), UDPHandler) srvr.serve_forever()
Contenido_Log = Hora_Log + ' Send to ' + IP_RegProxy + ':' + Puerto_RegProxy + ' ' + Line Content_Log(Path_Log, Contenido_Log) elif Line[0] == 'ACK': print('Enviando a Proxy Confirmacion ACK...') Contenido_Log = Hora_Log + ' Received from ' + IP_RegProxy + ':' + Puerto_RegProxy + ' ' + 'ACK' Content_Log(Path_Log, Contenido_Log) valores = self.Port_RTP_Client[Direccion_SIP] aEjecutar = './mp32rtp -i ' + '127.0.0.1' + ' -p ' + str( valores[0]) aEjecutar += ' < ' + Path_Audio print('Vamos a enviar el audio...', aEjecutar) os.system(aEjecutar) print('Audio enviado') elif Line[0] == 'BYE': Contenido_Log = Hora_Log + ' Received from ' + IP_RegProxy + ':' + Puerto_RegProxy + ' ' + Linea Content_Log(Path_Log, Contenido_Log) print('Enviando a Proxy Confirmacion BYE...') self.wfile.write(b'SIP/2.0 200 OK\r\n') Contenido_Log = Hora_Log + ' Send to ' + IP_RegProxy + ':' + Puerto_RegProxy + ' ' + 'SIP/2.0 200 OK' Content_Log(Path_Log, Contenido_Log) if __name__ == "__main__": serv = socketserver.UDPServer((IP_UAS, int(Puerto_UAS)), EchoHandler) print("Listening...") serv.serve_forever() Contenido_Log = '\n' + Hora_Log + ' Finishing...' Content_Log(Path_Log, Contenido_Log)
'gain', 'timing', 'mic_min', 'mic_max', 'x_min', 'x_max', 'y_min', 'y_max', 'z_min', 'z_max' ]) DB = None def init_db(): global DB if not DB or DB.closed != 0: DB = psycopg2.connect( "dbname='roommetrics' user='******' host='localhost' password='******'" ) DB.set_session(autocommit=True) init_db() class HandlePacket(socketserver.BaseRequestHandler): def handle(self): data = self.request[0].strip() data = Reading(*struct.unpack("<4f14H", data)) DB.cursor().execute('INSERT INTO data VALUES (NOW(), ' + ','.join(str(x) for x in data) + ');') if __name__ == "__main__": with socketserver.UDPServer(("0.0.0.0", 9942), HandlePacket) as server: server.serve_forever()
def runudp(port): with socketserver.UDPServer(('0.0.0.0', port), MyUDPHandler) as server: server.allow_reuse_address = True server.serve_forever()
self.Client_data[CORTES[1].split(':')[-1]] = atributos print("JULIA:", self.Client_data) if CORTES[3][:-4] != '0': tiempo = time_expire_str else: try: tiempo = time.strftime('%Y-%m-%d %H:%M:%S +%Z', time.gmtime(time.time())) self.Client_data[CORTES[1].split(':') [-1]].append(atributos) self.comprobar_cad_del() except KeyError: pass print("Datos cliente(IP, puerto): " + str(self.client_address)) print("El cliente nos manda ", DATA[:-4]) self.register2json() if __name__ == "__main__": Server_port = int(sys.argv[1]) serv = socketserver.UDPServer(('', Server_port), SIPRegisterHandler) print("Lanzando servidor UDP de eco...") try: serv.serve_forever() except KeyboardInterrupt: print("Finalizado servidor")
self.wfile.write(bytes(respuesta, 'utf-8')) write_log(message, received, server, str(port)) write_log(respuesta, sent_to, server, str(port)) else: port = self.user_dicc[user_sip][2] with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as my_socket: my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) my_socket.connect((server, port)) my_socket.send(line) data = my_socket.recv(1024) respuesta1 = b"SIP/2.0 400 Bad Request\r\n\r\n" respuesta2 = b"SIP/2.0 405 Method Not Allowed\r\n\r\n" if data != respuesta1 or data != respuesta2: self.wfile.write(data) if __name__ == '__main__': serv = socketserver.UDPServer((server, port), SIPHandler) print("Lanzando servidor UDP proxy ...") status = "Starting ... \r\n" Starting_Finishing(status) try: serv.serve_forever() except KeyboardInterrupt: status = "Finishing ...\r\n" Starting_Finishing(status) print("Finalizando servidor")
self.wfile.write(b"SIP/2.0 400 Bad Request\r\n\r\n") elif method == 'INVITE': self.wfile.write(b"SIP/2.0 100 Trying\r\n\r\n" + b"SIP/2.0 180 Ringing\r\n\r\n" + b"SIP/2.0 200 OK\r\n\r\n") elif method == 'ACK': aEjecutar = './mp32rtp -i 127.0.0.1 -p 23032 < ' + AUDIO_FILE print('Vamos a ejecutar', aEjecutar) os.system(aEjecutar) elif method == 'BYE': self.wfile.write(b"SIP/2.0 200 OK\r\n\r\n") elif method not in self.LISTA: self.wfile.write(b"SIP/2.0 405 Method Not Allowed\r\n\r\n") if __name__ == "__main__": if len(sys.argv) != 4: sys.exit('Usage: python3 server.py IP port audio_file') IP = sys.argv[1] PORT = int(sys.argv[2]) AUDIO_FILE = sys.argv[3] if not os.path.exists(AUDIO_FILE): sys.exit("Audio_file doesn't exists") # Creamos servidor de eco y escuchamos serv = socketserver.UDPServer((IP, PORT), EchoHandler) print("Lanzando servidor UDP de eco...") try: serv.serve_forever() except KeyboardInterrupt: print('servidor finalizado')
def __init__(self, host="0.0.0.0", udp_port=8053, tcp=False): self.host = host self.port = udp_port _log.info('Listening UDP request on {}:{}'.format(host, udp_port)) self.server = socketserver.UDPServer((host, udp_port), DNSHandler)
# Append new flows existing_data[time.time()] = [flow.data for flow in export.flows] with open(self.output_file, 'w') as fh: json.dump(existing_data, fh) if __name__ == "__main__": args = parser.parse_args() if args.debug: logging.getLogger().setLevel(logging.DEBUG) output_file = args.output_file SoftflowUDPHandler.set_output_file(output_file) host = args.host port = args.port logging.info("Listening on interface {}:{}".format(host, port)) server = socketserver.UDPServer((host, port), SoftflowUDPHandler) try: logging.debug("Starting the NetFlow listener") server.serve_forever(poll_interval=0.5) except (IOError, SystemExit): raise except KeyboardInterrupt: raise server.server_close()
if __name__ == "__main__": config = { 'account': ['username', 'passwd'], 'uaserver': ['ip', 'puerto'], 'rtpaudio': ['puerto'], 'regproxy': ['ip', 'puerto'], 'log': ['path'], 'audio': ['path'] } if len(sys.argv) != 2: sys.exit('Usage: python3 uaserver.py config') else: xml_file = sys.argv[1] parser = make_parser() xmlhandler = XMLHandler(config) parser.setContentHandler(xmlhandler) parser.parse(open(xml_file)) tags = xmlhandler.get_tags() log = Log_Writer(tags['log_path'], FORMATO) ip = tags['uaserver_ip'] puerto = int(tags['uaserver_puerto']) serv = socketserver.UDPServer((ip, puerto), EchoHandler) print("Comenzando servidor...\n") log.starting() try: serv.serve_forever() except KeyboardInterrupt: print("Finalizado servidor") log.finishing()
if ANSWER_WAS_FOUND: client.sendto(GAMEOVER_MESSAGE.encode(), self.client_address) return data = data.decode() try: data = int(data) except Exception: print("Bad input") return # print(data) if data == goal: ANSWER_WAS_FOUND = True client.sendto(SUCCESS_MESSAGE.encode(), self.client_address) print("Answer found.") elif data < goal: client.sendto(LESS_MESSAGE.encode(), self.client_address) elif data > goal: client.sendto(GREATER_MESSAGE.encode(), self.client_address) if __name__ == "__main__": address = ('localhost', 3000) server = socketserver.UDPServer(address, UDPHandler) print("Server is up and running ...") server.serve_forever()
self.lista = [] dic[usuario] = [self.client_address[0], time_exp_string] self.lista.append(dic) print("SIP/2.0 200 OK\r\n") self.wfile.write(b"SIP/2.0 200 OK" + b'\r\n\r\n') if line_client[4] == '0': print("Lo borramos del diccionario") del dic[usuario] print(self.lista) else: print(self.lista) self.register2json() if __name__ == "__main__": dic = {} try: PORT = int(sys.argv[1]) except IndexError: sys.exit("Debe introducir: server.py port_number") """Creamos UDP en el puerto que indicamos utilizando la clase.""" serv = socketserver.UDPServer(('', PORT), SIPRegistrerHandler) print("Iniciando servidor... \r\n") try: """Creamos el servidor""" serv.serve_forever() except KeyboardInterrupt: print("Finalizado servidor")
'utf-8') Content_Log(Path_Log, Contenido_Log) def register2json(self): """ Creacion fichero json """ json.dump(self.list_users, open('Registro_Usuarios.json', 'w')) def registered(self): """ Comprobacion existencia fichero json """ try: with open("Registro_Usuarios.json") as jsonFile: self.list_users = json.load(jsonFile) except: pass if __name__ == '__main__': serv = socketserver.UDPServer(('', int(Puerto_Proxy)), SIPRegisterHandler) print('Server ' + Name_Proxy + ' listening at port ' + Puerto_Proxy + '...') try: serv.serve_forever() except KeyboardInterrupt: print('Finalizado servidor') Contenido_Log = Hora_Log + ' Finishing...' Content_Log(Path_Log, Contenido_Log)
def get_server(cls, host, port): logging.info("Listening on interface {}:{}".format(host, port)) server = socketserver.UDPServer((host, port), cls) return server
def main(): HOST, PORT = "192.168.117.1", 9999 server = socketserver.UDPServer((HOST, PORT), MyUDPHandler) server.serve_forever()
while 1: # Lee línea a línea lo que nos envía el cliente. line = self.rfile.read() lista = ["INVITE", "ACK", "BYE"] lista_line_decode = line.decode("utf-8").split(" ") method = lista_line_decode[0] if not line: break if method == lista[0]: self.wfile.write(TRYING + RINGING + OK) print("El cliente nos manda " + line.decode('utf-8')) elif method == lista[1]: print("El cliente nos manda " + line.decode('utf-8')) aEjecutar = "mp32rtp -i 127.0.0.1 -p 23032 < " + AUDIO_FILE print("Vamos a ejecutar: " + aEjecutar) os.system(aEjecutar) elif method == lista[2]: self.wfile.write(OK) print("El cliente nos manda " + line.decode('utf-8')) elif method != lista: self.wfile.write(METHOD_NOT_ALLOWED) elif self.error(lista_line_decode): self.wfile.write(BAD_REQUEST) if __name__ == "__main__": # Creamos un servidor de eco y escuchamos. serv = socketserver.UDPServer(('', 6001), EchoHandler) print("Listening...") serv.serve_forever()
import socketserver class UDPHandler(socketserver.BaseRequestHandler): def handle(self): data, socket = self.request print(f'IP Address {self.client_address[0]}') print(f'Data: {data.decode()}') if __name__ == '__main__': with socketserver.UDPServer(('0.0.0.0', 8888), UDPHandler) as server: server.serve_forever()
data = self.request[0] socket = self.request[1] # print data freq, ind = struct.unpack("!ii", data[0:8]) data = data[8:] buff = struct.unpack(str(len(data) // 2).encode() + b"h", data) if not sound: sound = RawAudio(freq) print( f"input from {self.client_address[0]} @{freq} {len(data)} bytes" ) sound.putData(buff) socket.sendto(f"ACK {ind}".encode(), self.client_address) if __name__ == "__main__": HOST, PORT = "0.0.0.0", 9900 if SDL_Init(SDL_INIT_AUDIO) != 0: raise RuntimeError("Cannot initialize audio system: {}".format( SDL_GetError())) server = socketserver.UDPServer((HOST, PORT), MyUDPHandler) server.serve_forever() SDL_CloseAudioDevice(sound.devid) SDL_Quit(SDL_INIT_AUDIO)
import socketserver class LogHandler(socketserver.BaseRequestHandler): def handle(self): client = self.client_address[0] data = self.request[0].strip() print(client, "|", data.decode(errors='ignore')) if __name__ == "__main__": print('Starting a UDP listener on port 9000') with socketserver.UDPServer(("0.0.0.0", 9000), LogHandler) as server: server.serve_forever()
LOG_PATH = cHandler.config[2][1]['path'] log('Starting...') if cHandler.config[0][1]['ip'] != '': IP_PROXY = cHandler.config[0][1]['ip'] else: IP_PROXY = '127.0.0.1' PORT_PROXY = int(cHandler.config[0][1]['puerto']) NAME_PROXY = cHandler.config[0][1]['name'] PATH_Register = cHandler.config[1][1]['path'] PATH_Passwords = cHandler.config[1][1]['passwdpath'] allowed_users = [] passwd_file = open(PATH_Passwords, 'r') for line in passwd_file.readlines(): u = line.split(' ')[1] p = line.split(' ')[3][0:-1] d = {'user': u, 'password': p} allowed_users.append(d) serv = socketserver.UDPServer((IP_PROXY, PORT_PROXY), SIPRegisterHandler) print('Server ' + NAME_PROXY + ' listening at port ' + str(PORT_PROXY) + '...') try: serv.serve_forever() except KeyboardInterrupt: print("Server finished") log('Finishing.')
def start(host='localhost', port=9999): with socketserver.UDPServer((host, port), UDPHandler) as server: logger.info('Server started at {}:{}'.format(host, port)) server.serve_forever()
# def finish(self): # self.ser.close() def sendMessage(serial, message): #发送给控制板信息,并读取控制板传来的信息 if serial: serial.write(message.encode('utf-8')) time.sleep(0.07) allMessage = serial.read(ser.inWaiting()) return allMessage else: return 0 if __name__ == '__main__': port = read_ports() if port: ser = serial.Serial(port[0], 9600) #time.sleep(1.0) server = socketserver.UDPServer(("192.168.31.20", 8080), udpServer) #使用处理单连接的UDPServer while True: server.handle_request() if message: mes = sendMessage(ser, message) print(mes) else: print("connect error")
''' LOG.''' datos_log2 = str_now + " Received " datos_log2 += dataipdata + ":" + dataportdata datos_log2 += " SIP/2.0 200 OK" + "\r\n" fich.write(datos_log2) self.wfile.write(b"SIP/2.0 200 OK\r\n\r\n") ''' LOG.''' datos_log3 = str_now + " Sent to " datos_log3 += self.client_address[0] + ":" datos_log3 += str(self.client_address[1]) datos_log3 += " SIP/2.0 200 OK" + "\r\n" fich.write(datos_log3) #Ahora debemos volver a entrar en el fichero y # coger para el usuario sip # su puerto del servidor para poder enviarle un ACK # Si no hay más líneas salimos del bucle infinito if not line: break if __name__ == "__main__": # Creamos servidor de eco y escuchamos serv = socketserver.UDPServer((PROXY_IP, int(PROXY_PORT)), EchoHandler) print("Server " + PROXY_NAME + " listening at port " + PROXY_PORT + " ...") try: serv.serve_forever() except KeyboardInterrupt: print("Finalizado PROXY")
format='%(asctime)s - %(message)s', # 字符串格式 datefmt='%Y/%m/%d %H:%M:%S', # 时间格式 filename=log_file, # log文件 filemode='a') # 追加模式 class SyslogUDPHandler(socketserver.BaseRequestHandler): def handle(self): data = bytes.decode(self.request[0].strip()) # 读取数据 # ============可以配置过滤器仅仅读取接口up/down信息=============== # if re.match('.*changed state to administratively down.*', data): # print( "%s : " % self.client_address[0], str(data)) # elif re.match('.*changed state to up.*', data): # print( "%s : " % self.client_address[0], str(data)) print("%s : " % self.client_address[0], str(data)) # 打印syslog信息 logging.info(f"source_ip: {self.client_address[0]} - message: {str(data)}") # 把信息logging到本地, logging level为INFO if __name__ == "__main__": # 使用Linux解释器 & WIN解释器 try: HOST, PORT = "0.0.0.0", 514 # 本地地址与端口 server = socketserver.UDPServer((HOST, PORT), SyslogUDPHandler) # 绑定本地地址,端口和syslog处理方法 print("Syslog 服务已启用, 写入日志到文本文件!!!") server.serve_forever(poll_interval=0.5) # 运行服务器,和轮询间隔 except (IOError, SystemExit): raise except KeyboardInterrupt: # 捕获Ctrl+C,打印信息并退出 print("Crtl+C Pressed. Shutting down.")
import socketserver class UDPHandler(socketserver.BaseRequestHandler): def handle(self): data, socket = self.request print('Address: {}\nData: {}'.format(self.client_address[0], data.decode())) socket.sendto(data, self.client_address) if __name__ == '__main__': with socketserver.UDPServer(('localhost', 8000), UDPHandler) as server: server.serve_forever()
red = rgb % 1000 green = rgb // 1000 % 1000 blue = rgb // 1000000 hsv = colorsys.rgb_to_hsv(red / 100, green / 100, blue / 100) hue = int(hsv[0] * 65565) sat = int(hsv[1] * 255) bri = int(hsv[2] * 255) print("Setting light {} to HSV values {} {} {}" .format(light_id, hue, sat, bri)) request_data = {"on": True, "hue": hue, "bri": bri, "sat": sat} r = requests.put("http://localhost/api/{}/lights/{}/state" .format(APIKEY, light_id), json=request_data) print("Response:", r.status_code) def get_lights(): r = requests.get("http://localhost/api/{}/lights".format(APIKEY)) if r.status_code == 200: data = r.json() if __name__ == "__main__": HOST, PORT = "", 7777 print("establish UDP server ...") udp_server = socketserver.UDPServer((HOST, PORT), HueUDPHandler) udp_server.serve_forever()
# use SGACL information to prepare Ansible playbook acl_in_playbook = [] for ACE in SGACL_content_list: ace = 'access-list ' + SGACL_name + ' ' + ACE acl_in_playbook.append(ace) with open('env/extravars') as f: doc = yaml.load(f, Loader=yaml.FullLoader) doc['acl_name'] = SGACL_name doc['acl_entries'] = acl_in_playbook with open('env/extravars', 'w') as f: yaml.safe_dump(doc, f) # run Ansible playbook to apply ACL to ASA r = ansible_runner.run(private_data_dir='.', playbook='asa_acl.yml') logging.info( "Ansible playbook run on ASA with following results: " + str(r.stats)) # add logging statement if __name__ == "__main__": # start the UDP Server try: server = socketserver.UDPServer((HOST, PORT), SyslogUDPHandler) server.serve_forever(poll_interval=0.5) except (IOError, SystemExit): raise except KeyboardInterrupt: print("Crtl+C Pressed. Shutting down.")
":" + rec_port + ": " + \ respubye.replace("\r\n", " ") log.write(hora + " " + logmen + "\n") else: print("---->> " + lineutf) if not line: break if __name__ == "__main__": try: XML = sys.argv[1] except: print("Usage: python3 proxy_registrar.py <file.xml>") proxyobj = proxyxml(XML) ProxySIPHandler.diccionario = proxyobj.diccionario proxyname = proxyobj.diccionario["servname"] proxyport = proxyobj.diccionario["servport"] proxyip = proxyobj.diccionario["servip"] logpath = proxyobj.diccionario["logpath"] log = open(logpath, 'w') hora = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) logmen = "Starting..." log.write(hora + " " + logmen + "\n") my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) serv = socketserver.UDPServer((proxyip, int(proxyport)), ProxySIPHandler) print("Server " + proxyname + " listening at port " + proxyport + "...") serv.serve_forever()
if metodo not in ["INVITE", "BYE", "ACK"]: self.wfile.write(b"SIP/2.0 405 Method Not Allowed" + b"\r\n") elif metodo == "INVITE": self.wfile.write(b"SIP/2.0 100 Trying" + b"\r\n") self.wfile.write(b"SIP/2.0 180 Ring" + b"\r\n") self.wfile.write(b"SIP/2.0 200 OK" + b"\r\n") elif metodo == "ACK": aEjecutar = "mp32rtp -i " + IP + " -p 23032 < " + fichero_audio print("Vamos a ejecutar", aEjecutar) os.system(aEjecutar) elif metodo == "BYE": self.wfile.write(b"SIP/2.0 200 OK" + b"\r\n") else: self.wfile.write(b"SIP/2.0 400 Bad Request" + b"\r\n") if __name__ == "__main__": # Creamos servidor de eco y escuchamos if len(sys.argv) == 4: IP = sys.argv[1] Port_serv = int(sys.argv[2]) fichero_audio = sys.argv[3] if os.path.exists(fichero_audio): serv = socketserver.UDPServer((IP, Port_serv), EchoHandler) print("Listening") serv.serve_forever() else: sys.exit("Usage: python server.py IP port audio_file") else: sys.exit("Usage: python server.py IP port audio_file")
DATOS_XML = U2HANDLER.get_tags() # Extraigo el fichero XML USERNAME = DATOS_XML['account_username'] # Es el nombre SIP RTP_PORT = int(DATOS_XML['rtpaudio_puerto']) # Es el puerto del RTP PROX_PORT = int(DATOS_XML['regproxy_puerto']) # Es el puerto del PROXY LOG_PATH = DATOS_XML['log_path'] # Es el fichero log AUDIO_PATH = DATOS_XML['audio_path'] # Es el audio log UASERV_PORT = DATOS_XML['uaserver_puerto'] # Es el port del servidor if DATOS_XML['uaserver_ip'] == '': # En caso de no tener IP el servido UASERV_IP = '127.0.0.1' # Por defecto es 127.0.0.1 else: UASERV_IP = DATOS_XML['uaserver_ip'] # Si no esta vacia, es xml if DATOS_XML['regproxy_ip'] == '': # En caso de no tener IP el Proxy PROXY_IP = '127.0.0.1' # Por defecto es 127.0.0.1 else: PROXY_IP = DATOS_XML['regproxy_ip'] # Si no esta vacia, es ip xml SERVI = socketserver.UDPServer((UASERV_IP, int(UASERV_PORT)), EchoHandler) print('Listening...\r\n') try: SERVI.serve_forever() except IndexError: sys.exit("Usage: python3 uaserver.py config") except KeyboardInterrupt: print("\r\nFinalizado el servidor") else: sys.exit('Usage: python3 uaserver.py config')