def _bootstrap(self, parent_sentinel=None): from . import util, context global _current_process, _parent_process, _process_counter, _children try: if self._start_method is not None: context._force_start_method(self._start_method) _process_counter = itertools.count(1) _children = set() util._close_stdin() old_process = _current_process _current_process = self _parent_process = _ParentProcess(self._parent_name, self._parent_pid, parent_sentinel) if threading._HAVE_THREAD_NATIVE_ID: threading.main_thread()._set_native_id() try: util._finalizer_registry.clear() util._run_after_forkers() finally: # delay finalization of the old process object until after # _run_after_forkers() is executed del old_process util.info('child process calling self.run()') try: self.run() exitcode = 0 finally: util._exit_function() except SystemExit as e: if not e.args: exitcode = 1 elif isinstance(e.args[0], int): exitcode = e.args[0] else: sys.stderr.write(str(e.args[0]) + '\n') exitcode = 1 except: exitcode = 1 import traceback sys.stderr.write('Process %s:\n' % self.name) traceback.print_exc() finally: threading._shutdown() util.info('process exiting with exitcode %d' % exitcode) util._flush_std_streams() return exitcode
def _bootstrap(self): from . import util, context global _current_process, _process_counter, _children try: if self._start_method is not None: context._force_start_method(self._start_method) _process_counter = itertools.count(1) _children = set() util._close_stdin() old_process = _current_process _current_process = self try: util._finalizer_registry.clear() util._run_after_forkers() finally: # delay finalization of the old process object until after # _run_after_forkers() is executed del old_process util.info('child process calling self.run()') try: self.run() exitcode = 0 finally: util._exit_function() except SystemExit as e: if not e.args: exitcode = 1 elif isinstance(e.args[0], int): exitcode = e.args[0] else: sys.stderr.write(str(e.args[0]) + '\n') exitcode = 1 except: exitcode = 1 import traceback sys.stderr.write('Process %s:\n' % self.name) traceback.print_exc() finally: threading._shutdown() util.info('process exiting with exitcode %d' % exitcode) sys.stdout.flush() sys.stderr.flush() return exitcode
def communicate(): while True: logging.info("Client ran for: ", str(time.time() - start_time)) decoded = input(">") # chuyển byte sang str logging.info(decoded) #for debug GPIO.output(18, True) sleep(0.5) GPIO.output(18, False) if decoded == Commands.detectface: x = threading.Thread(target=startfacedt, args=(False, )) x.start() logging.critical("STARTED") while True: state = input(">") # chuyển byte sang str logging.critical("recv ", state) print(state) print(state.format()) if state == Commands.stopdetect: threading._shutdown() GPIO.output(12, False) pwm.stop() GPIO.cleanup() break if decoded == "stop music": pygame.mixer.music.stop() if decoded == Commands.playussr: pygame.mixer.init() pygame.mixer.music.load("USSR.mp3") pygame.mixer.music.play() GPIO.output(18, True) #while pygame.mixer.music.get_busy() == True: # continue if decoded == Commands.Quit: break
class GuiClient: def conn(self): global client client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((GUI_SERVER, GUI_PORT)) def send(self, object): client.sendall((object + "\n").encode()) #to utf8 def getline(self): alldata = b"" while (newdata := client.recv(1024)) != b'': alldata += newdata #print (alldata) if b"\n" in alldata: return alldata.decode('utf-8').rstrip() print("Disconnected, no data !!!") client.close() threading._shutdown()
def _execute(self, queue, tasks, log, locks, queue_lock, all_task_ids): """ Executes the given tasks. Returns a boolean indicating whether the tasks were executed successfully. """ # The tasks must use the same function. assert len(tasks) task_func = tasks[0].serialized_func assert all([task_func == task.serialized_func for task in tasks[1:]]) # Before executing periodic tasks, queue them for the next period. if task_func in self.tiger.periodic_task_funcs: tasks[0]._queue_for_next_period() with g_fork_lock: child_pid = os.fork() if child_pid == 0: # Child process log = log.bind(child_pid=os.getpid()) # Disconnect the Redis connection inherited from the main process. # Note that this doesn't disconnect the socket in the main process. self.connection.connection_pool.disconnect() random.seed() # Ignore Ctrl+C in the child so we don't abort the job -- the main # process already takes care of a graceful shutdown. signal.signal(signal.SIGINT, signal.SIG_IGN) success = self._execute_forked(tasks, log) # Wait for any threads that might be running in the child, just # like sys.exit() would. Note we don't call sys.exit() directly # because it would perform additional cleanup (e.g. calling atexit # handlers twice). See also: https://bugs.python.org/issue18966 threading._shutdown() os._exit(int(not success)) else: # Main process log = log.bind(child_pid=child_pid) for task in tasks: log.info('processing', func=task_func, task_id=task.id, params={ 'args': task.args, 'kwargs': task.kwargs }) # Attach a signal handler to SIGCHLD (sent when the child process # exits) so we can capture it. signal.signal(signal.SIGCHLD, sigchld_handler) # Since newer Python versions retry interrupted system calls we can't # rely on the fact that select() is interrupted with EINTR. Instead, # we'll set up a wake-up file descriptor below. # Create a new pipe and apply the non-blocking flag (required for # set_wakeup_fd). pipe_r, pipe_w = os.pipe() flags = fcntl.fcntl(pipe_w, fcntl.F_GETFL, 0) flags = flags | os.O_NONBLOCK fcntl.fcntl(pipe_w, fcntl.F_SETFL, flags) # A byte will be written to pipe_w if a signal occurs (and can be # read from pipe_r). old_wakeup_fd = signal.set_wakeup_fd(pipe_w) def check_child_exit(): """ Do a non-blocking check to see if the child process exited. Returns None if the process is still running, or the exit code value of the child process. """ try: pid, return_code = os.waitpid(child_pid, os.WNOHANG) if pid != 0: # The child process is done. return return_code except OSError as e: # Of course EINTR can happen if the child process exits # while we're checking whether it exited. In this case it # should be safe to retry. if e.errno == errno.EINTR: return check_child_exit() else: raise # Wait for the child to exit and perform a periodic heartbeat. # We check for the child twice in this loop so that we avoid # unnecessary waiting if the child exited just before entering # the while loop or while renewing heartbeat/locks. while True: return_code = check_child_exit() if return_code is not None: break # Wait until the timeout or a signal / child exit occurs. try: select.select([pipe_r], [], [], self.config['ACTIVE_TASK_UPDATE_TIMER']) except select.error as e: if e.args[0] != errno.EINTR: raise return_code = check_child_exit() if return_code is not None: break try: self._heartbeat(queue, all_task_ids) for lock in locks: lock.renew(self.config['ACTIVE_TASK_UPDATE_TIMEOUT']) if queue_lock: queue_lock.renew( self.config['ACTIVE_TASK_UPDATE_TIMEOUT']) except OSError as e: # EINTR happens if the task completed. Since we're just # renewing locks/heartbeat it's okay if we get interrupted. if e.errno != errno.EINTR: raise # Restore signals / clean up signal.signal(signal.SIGCHLD, signal.SIG_DFL) signal.set_wakeup_fd(old_wakeup_fd) os.close(pipe_r) os.close(pipe_w) success = (return_code == 0) return success
def stop_all(self): threading._shutdown()
res = requests.get( "http://localhost:8080/noauth/echo/query?hello=world") self.assertEqual(json.loads(res.text), {"hello": "world"}, "Query get no auth not correctly echoed") def test_query_get_auth(self): res = requests.get("http://localhost:8080/auth/echo/query?hello=world", headers={"Authorization": "testauth"}) self.assertEqual(json.loads(res.text), {"hello": "world"}, "Query get no auth not correctly echoed") def test_query_post_no_auth(self): res = requests.post("http://localhost:8080/noauth/echo/query", data={"hello": "world"}) self.assertEqual(json.loads(res.text), {"hello": "world"}, "Query get no auth not correctly echoed") def test_query_post_auth(self): res = requests.post("http://localhost:8080/auth/echo/query", data={"hello": "world"}, headers={"Authorization": "testauth"}) self.assertEqual(json.loads(res.text), {"hello": "world"}, "Query get no auth not correctly echoed") if __name__ == "__main__": threading._start_new_thread(set_up_server, ()) time.sleep(1) unittest.main() threading._shutdown() exit()
def update_event(self, inp=-1): self.set_output_val(0, threading._shutdown())
def __del__( self ): self.Stop() threading._shutdown()
def stop(self): print("Stopping VideoStream...") threading._shutdown() self.socket.close() self.status = "down"
def close(self): print('closing...') threading._shutdown() pg.quit() sys.exit()
def communicate(): while True: rantime = time.time() - start_time rantime = int(rantime) timeranstr = "Client ran for: " + str(rantime) writeloginf(timeranstr) sendserver = "0" data = s.recv(1024) decoded = data.decode() # chuyển byte sang str writeloginf(decoded) #for debug GPIO.output(18, True) sleep(0.5) GPIO.output(18, False) if decoded == Commands.testalarm: sendserver = "1" try: s.send(sendserver.encode()) except: writwritelogerr("Cannot sent to server") playalarm() if decoded == Commands.setalarm: pygame.mixer.init() schedule.every().day.at('14:00').do(playalarm) sendserver = "1" try: s.send(sendserver.encode()) except: writwritelogerr("Cannot sent to server") while True: schedule.run_pending() sleep(30) if GPIO.input(22) == GPIO.HIGH: writeloginf("pressed") musicdic = os.listdir("./music/") randomsong = random.choice(musicdic) randomsong = "./music/" + randomsong pygame.mixer.music.load(randomsong) pygame.mixer.music.play() if pygame.mixer.music.get_busy() == False: if GPIO.input(26) == GPIO.HIGH: writeloginf("pressed") musicdic = os.listdir("./music/") randomsong = random.choice(musicdic) randomsong = "./music/" + randomsong pygame.mixer.music.load(randomsong) pygame.mixer.music.play() else: if GPIO.input(26) == GPIO.HIGH: pygame.mixer.music.stop() #else: # try: # randomsong = random.choice(musicdic) # randomsong = "./music/" + randomsong # pygame.mixer.music.load(randomsong) # pygame.mixer.music.play() # except: # wrwritelogerr("Error ocurred") if decoded == Commands.testspeech: writeloginf("ohayo :)") try: pygame.mixer.init() pygame.mixer.music.load("goodmorning.mp3") pygame.mixer.music.play() except: wrwritelogerr("Error ocurred") GPIO.output(18, True) sendserver = "1" while pygame.mixer.music.get_busy() == True: GPIO.output(12, False) sleep(0.05) GPIO.output(12, True) continue try: s.send(sendserver.encode()) except: writwritelogerr("Cannot sent to server") if decoded == Commands.detectface: sendserver = "1" try: s.send(sendserver.encode()) except: writwritelogerr("Cannot sent to server") x = threading.Thread(target=startfacedt, args=(False, )) x.start() logging.critical("STARTED") while True: data = s.recv(1024) state = data.decode() # chuyển byte sang str logging.critical("recv ", state) print(state) print(state.format()) sendserver = "1" if state == 'stop facedetect': threading._shutdown() GPIO.output(12, False) sendserver = "1" break try: s.send(sendserver.encode()) except: writwritelogerr("Cannot sent to server") if decoded == Commands.readlog: files = os.listdir("./LogFiles/") files.sort() writeloginf(("Found ", str(len(files)), " file(s):")) for file in files: print(files.index(file), " : ", file) # with open(file, 'r') as f: # data = f.read() print("Read file:") getfilenum = input(">") try: getfilenum = int(getfilenum) test = files[getfilenum] except: writelogerr("File index not found") else: getfilenum = int(getfilenum) path = "./LogFiles/" + files[getfilenum] f = open(str(path), 'r') data = f.read() print(data) sendserver = "1" # with open() if decoded == Commands.stopmusic: pygame.mixer.music.stop() sendserver = "1" if decoded == Commands.playussr: pygame.mixer.init() pygame.mixer.music.load("USSR.mp3") pygame.mixer.music.play() GPIO.output(18, True) sendserver = "1" #while pygame.mixer.music.get_busy() == True: # continue if decoded == Commands.Quit: sendserver = "9" try: s.send(sendserver.encode()) except: writwritelogerr("Cannot sent to server") break try: s.send(sendserver.encode()) except: writwritelogerr("Cannot sent to server")
def Test_Start(Malware): global pid Sleep_time = LauncherConf.test_time open_proc = subprocess.Popen( '%s /BackingFile %s/%s.PML' % (LauncherConf.Procmon_Path, LauncherConf.LogFile_Path, Malware[0:len(Malware) - 4])) time.sleep(5) # minimize procmon--------------------------------------------------------------------- time.sleep(2) minimize = win32gui.GetForegroundWindow() print("should be procmon: " + win32gui.GetWindowText(minimize)) win32gui.ShowWindow(minimize, win32con.SW_MINIMIZE) # ------------------------------------------------------------------------------------- ServerConnection("ProcMon Launched") try: malware_path = '%s/%s' % (LauncherConf.Malwares_Resources_Path, Malware) if LauncherConf.use_shortcut: malware_path = '%s' % (get_shortcut_target( LauncherConf.Malwares_Resources_Path, Malware)) write2LogFile("shortcut path: " + malware_path) process = subprocess.Popen(malware_path) time.sleep(5) ServerConnection("Malware Launched") except: time.sleep(30) ServerConnection("Malware Launched FAILED") ServerConnection("END") exit() pid = process.pid #monkey================================ if LauncherConf.use_monkey: write2LogFile("come into monkey") pyautogui.click( win32api.GetSystemMetrics(0) / 2, win32api.GetSystemMetrics(1) / 2) window_title = win32gui.GetWindowText(win32gui.GetForegroundWindow()) write2LogFile("should be window title: " + window_title) t = threading.Thread(target=PyWinMonkeyLib.GoSimulate, args=(window_title, int(Sleep_time / 2), 5, False)) t.start() threading._shutdown() #====================================== time.sleep(Sleep_time) ServerConnection("Process finished") terminate_proc = subprocess.Popen('%s /Terminate' % (LauncherConf.Procmon_Path)) terminate_proc.wait() if LauncherConf.convertPML2CSV: convert2csv = subprocess.Popen( '%s /OpenLog %s\\%s.PML /SaveAs %s\\%s.csv' % (LauncherConf.Procmon_Path, LauncherConf.LogFile_Path, Malware[0:len(Malware) - 4], LauncherConf.LogFile_Path, Malware[0:len(Malware) - 4])) convert2csv.wait() ServerConnection("PML Converted to csv") return True
def _execute(self, queue, tasks, log, locks, queue_lock, all_task_ids): """ Executes the given tasks. Returns a boolean indicating whether the tasks were executed successfully. """ # The tasks must use the same function. assert len(tasks) task_func = tasks[0].serialized_func assert all([task_func == task.serialized_func for task in tasks[1:]]) # Before executing periodic tasks, queue them for the next period. if task_func in self.tiger.periodic_task_funcs: tasks[0]._queue_for_next_period() with g_fork_lock: child_pid = os.fork() if child_pid == 0: # Child process log = log.bind(child_pid=os.getpid()) # Disconnect the Redis connection inherited from the main process. # Note that this doesn't disconnect the socket in the main process. self.connection.connection_pool.disconnect() random.seed() # Ignore Ctrl+C in the child so we don't abort the job -- the main # process already takes care of a graceful shutdown. signal.signal(signal.SIGINT, signal.SIG_IGN) with WorkerContextManagerStack(self.config['CHILD_CONTEXT_MANAGERS']): success = self._execute_forked(tasks, log) # Wait for any threads that might be running in the child, just # like sys.exit() would. Note we don't call sys.exit() directly # because it would perform additional cleanup (e.g. calling atexit # handlers twice). See also: https://bugs.python.org/issue18966 threading._shutdown() os._exit(int(not success)) else: # Main process log = log.bind(child_pid=child_pid) for task in tasks: log.info('processing', func=task_func, task_id=task.id, params={'args': task.args, 'kwargs': task.kwargs}) # Attach a signal handler to SIGCHLD (sent when the child process # exits) so we can capture it. signal.signal(signal.SIGCHLD, sigchld_handler) # Since newer Python versions retry interrupted system calls we can't # rely on the fact that select() is interrupted with EINTR. Instead, # we'll set up a wake-up file descriptor below. # Create a new pipe and apply the non-blocking flag (required for # set_wakeup_fd). pipe_r, pipe_w = os.pipe() flags = fcntl.fcntl(pipe_w, fcntl.F_GETFL, 0) flags = flags | os.O_NONBLOCK fcntl.fcntl(pipe_w, fcntl.F_SETFL, flags) # A byte will be written to pipe_w if a signal occurs (and can be # read from pipe_r). old_wakeup_fd = signal.set_wakeup_fd(pipe_w) def check_child_exit(): """ Do a non-blocking check to see if the child process exited. Returns None if the process is still running, or the exit code value of the child process. """ try: pid, return_code = os.waitpid(child_pid, os.WNOHANG) if pid != 0: # The child process is done. return return_code except OSError as e: # Of course EINTR can happen if the child process exits # while we're checking whether it exited. In this case it # should be safe to retry. if e.errno == errno.EINTR: return check_child_exit() else: raise # Wait for the child to exit and perform a periodic heartbeat. # We check for the child twice in this loop so that we avoid # unnecessary waiting if the child exited just before entering # the while loop or while renewing heartbeat/locks. while True: return_code = check_child_exit() if return_code is not None: break # Wait until the timeout or a signal / child exit occurs. try: select.select([pipe_r], [], [], self.config['ACTIVE_TASK_UPDATE_TIMER']) except select.error as e: if e.args[0] != errno.EINTR: raise return_code = check_child_exit() if return_code is not None: break try: self._heartbeat(queue, all_task_ids) for lock in locks: lock.renew(self.config['ACTIVE_TASK_UPDATE_TIMEOUT']) if queue_lock: acquired, current_locks = queue_lock.renew() if not acquired: log.debug('queue lock renew failure') except OSError as e: # EINTR happens if the task completed. Since we're just # renewing locks/heartbeat it's okay if we get interrupted. if e.errno != errno.EINTR: raise # Restore signals / clean up signal.signal(signal.SIGCHLD, signal.SIG_DFL) signal.set_wakeup_fd(old_wakeup_fd) os.close(pipe_r) os.close(pipe_w) success = (return_code == 0) return success