def close(self): """Close all communications channels with the child.""" if self.closed: return os.close(self.child_fd) CloseHandle(self.stdout_handle) CloseHandle(self.stderr_handle) # File descriptors are closed, nothing can be added to the queue # anymore. Empty it in case a thread was blocked on put(). while self.child_output.qsize(): self.child_output.get() # Now the threads are ready to be joined. self.stdout_reader.join() self.stderr_reader.join() self.closed = True
def kill_scdaemon(): killed = False try: # Works for Windows. from win32com.client import GetObject from win32api import OpenProcess, CloseHandle, TerminateProcess wmi = GetObject("winmgmts:") ps = wmi.InstancesOf("Win32_Process") for p in ps: if p.Properties_("Name").Value == "scdaemon.exe": pid = p.Properties_("ProcessID").Value handle = OpenProcess(1, False, pid) TerminateProcess(handle, -1) CloseHandle(handle) killed = True except ImportError: # Works for Linux and OS X. return_code = subprocess.call(["/usr/bin/pkill", "-9", "scdaemon"]) # nosec if return_code == 0: killed = True if killed: sleep(0.1) return killed
def getStatusBarItems(self, hwnd, buf_len=512): """If success, return statusbar texts like list of strings. Otherwise return either '>>> No process ! <<<' or '>>> No parts ! <<<'. Mandatory argument: handle of statusbar. Option argument: length of text buffer.""" pid = GetWindowThreadProcessId(hwnd)[1] process = _kernel32.OpenProcess( PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, False, pid) res_val = ['>>> No process ! <<<'] if process: parts = win32guiSendMessage(hwnd, SB_GETPARTS, 0, 0) partList = [] res_val = ['>>> No parts ! <<<'] if parts > 0: remBuf = _kernel32.VirtualAllocEx(process, None, buf_len, MEM_COMMIT, PAGE_READWRITE) locBuf = create_unicode_buffer(buf_len) for item in range(parts): win32guiSendMessage(hwnd, SB_GETTEXTW, item, remBuf) _kernel32.ReadProcessMemory(process, remBuf, locBuf, buf_len, None) #copy remBuf to locBuf partList.append(locBuf.value) res_val = partList _kernel32.VirtualFreeEx(process, remBuf, 0, MEM_RELEASE) CloseHandle(process) return res_val
def kill_scdaemon(): killed = False try: # Works for Windows. from win32com.client import GetObject from win32api import OpenProcess, CloseHandle, TerminateProcess wmi = GetObject('winmgmts:') ps = wmi.InstancesOf('Win32_Process') for p in ps: if p.Properties_('Name').Value == 'scdaemon.exe': pid = p.Properties_('ProcessID').Value handle = OpenProcess(1, False, pid) TerminateProcess(handle, -1) CloseHandle(handle) killed = True except ImportError: # Works for Linux and OS X. pids = subprocess.check_output( "ps ax | grep scdaemon | grep -v grep | awk '{ print $1 }'", shell=True).strip() if pids: for pid in pids.split(): subprocess.call(['kill', '-9', pid]) killed = True if killed: time.sleep(0.1) return killed
def kill_process_win32(pid): """ Call to system Windows API ``TerminateProcess`` method. """ try: from win32api import TerminateProcess, OpenProcess, CloseHandle except: lg.exc() return False try: PROCESS_TERMINATE = 1 handle = OpenProcess(PROCESS_TERMINATE, False, pid) except: lg.out(2, 'bpio.kill_process_win32 can not open process %d' % pid) return False try: TerminateProcess(handle, -1) except: lg.out(2, 'bpio.kill_process_win32 can not terminate process %d' % pid) return False try: CloseHandle(handle) except: lg.exc() return False return True
def _FindDatabaseFolder(self, wechat_id): """取默认数据库存放路径""" key_handle = OpenKey(HKEY_CURRENT_USER, r"Software\Tencent\WeChat") folder, _ = QueryValueEx(key_handle, 'FileSavePath') CloseHandle(key_handle) if folder == 'MyDocument:': folder = self._FindMyDocPath() return os.path.join(folder, 'WeChat Files', wechat_id, 'Msg')
def kill(self): try: PROCESS_TERMINATE = 1 handle = OpenProcess(PROCESS_TERMINATE, False, self.pid) TerminateProcess(handle, -1) CloseHandle(handle) except: pass
def _FindMyDocPath(self): """取得“我的文档”的路径""" key_handle = OpenKey( HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" ) path, _ = QueryValueEx(key_handle, 'Personal') CloseHandle(key_handle) return path
def getListViewItems(self, hwnd): col = LVCOLUMN() col.mask = LVCF_FMT | LVCF_IMAGE | LVCF_ORDER | LVCF_SUBITEM | LVCF_TEXT | LVCF_WIDTH pid = GetWindowThreadProcessId(hwnd)[1] hProcHnd = _kernel32.OpenProcess(PROCESS_ALL_ACCESS, False, pid) pLVI = _kernel32.VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) col.cchTextMax = 2000 col.pszText = pLVI + sizeof(col) + 1 ret = _kernel32.WriteProcessMemory(hProcHnd, pLVI, addressof(col), sizeof(col), 0) if not ret: raise WinError() retval = 1 col_count = 0 while retval: # Columns enumeration try: retval = win32guiSendMessage(hwnd, LVM_GETCOLUMN, col_count, pLVI) except: retval = 0 raise col_count += 1 pBuffer = _kernel32.VirtualAllocEx(hProcHnd, 0, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) lvitem_str = 20 * "\x00" + pack_int(pBuffer) + pack_int( 4096) + 8 * "\x00" lvitem_buffer = create_string_buffer(lvitem_str) num_items = win32guiSendMessage(hwnd, LVM_GETITEMCOUNT) res = [] for column_index in range(col_count): lvitem_buffer.__setslice__( 8, 12, pack_int(column_index)) #column index increment _kernel32.WriteProcessMemory(hProcHnd, pLVI, addressof(lvitem_buffer), sizeof(lvitem_buffer), 0) target_buff = create_string_buffer(4096) item_texts = [] for item_index in range(num_items): if self.only_sel: if not win32guiSendMessage(hwnd, LVM_GETITEMSTATE, item_index, LVIS_SELECTED): continue win32guiSendMessage(hwnd, LVM_GETITEMTEXT, item_index, pLVI) _kernel32.ReadProcessMemory(hProcHnd, pBuffer, addressof(target_buff), 4096, 0) item_texts.append(target_buff.value) res.append(item_texts) _kernel32.VirtualFreeEx(hProcHnd, pBuffer, 0, MEM_RELEASE) _kernel32.VirtualFreeEx(hProcHnd, pLVI, 0, MEM_RELEASE) CloseHandle(hProcHnd) return map( list, zip(*res)) #Transposing Two-Dimensional Arrays by Steve Holden
def Init(self, offset_wechat_id, offset_db_key_pointer, process_name='wechat.exe'): # 似乎有其他进程名的需求 """使用前需要调用,失败抛出 WechatDatabaseDecryptException offset_wechat_id: 存放 wechat id 得指针的地址相对于 wechatwin.dll 的偏移 offset_db_key_pointer: 存放数据库密码的指针的地址相对于 wechatwin.dll 的偏移 偏移依赖于特定微信版本 """ pid = self._GetPidFromProcessName(process_name) if not pid: raise WechatDatabaseDecryptException( "进程 {process_name} 不存在".format(process_name)) process_handle = OpenProcess(PROCESS_ALL_ACCESS, False, pid) if not process_handle: raise WechatDatabaseDecryptException("打开进程 {pid} 失败".format(pid)) module_name = 'wechatwin.dll' module_address = self._FindProcessModuleAddress( process_handle, module_name) if not module_address: CloseHandle(process_handle) raise WechatDatabaseDecryptException( "模块 {module_name} 不存在".format(module_name)) wechat_id = self._ReadWechatId(process_handle, module_address + offset_wechat_id) if not wechat_id: CloseHandle(process_handle) raise WechatDatabaseDecryptException("读取 wechat id 失败") raw_key = self._ReadDatabaseRawKey( process_handle, module_address + offset_db_key_pointer) if not raw_key: CloseHandle(process_handle) raise WechatDatabaseDecryptException("读取 key 失败") CloseHandle(process_handle) self.m_raw_key = raw_key self.m_wechat_id = wechat_id self.m_db_folder = self._FindDatabaseFolder(wechat_id)
def _terminate_qprocess(self): try: py_proc = psutil.Process(self.process.pid()).children()[0].pid except psutil.NoSuchProcess: return children = psutil.Process(py_proc).children() if not IS_WINDOWS: os.kill(py_proc, SIGKILL) for child in children: os.kill(child.pid, SIGKILL) if IS_WINDOWS: TerminateProcess(py_proc, -1) CloseHandle(py_proc) for child in children: TerminateProcess(child.pid, -1) CloseHandle(child.pid)
def stop(self, force=True): if self.poll() is not None: return True try: PROCESS_TERMINATE = 1 handle = OpenProcess(PROCESS_TERMINATE, False, self.pid) TerminateProcess(handle, -1) CloseHandle(handle) except subprocess.pywintypes.error, e: # @TODO: check error code warnings.warn(e)
def CreateNameEventWait(name, timeout=-1): # print("create event = [" + name + "]") # 根据名字搞个Event event = win32event.CreateEvent(None, True, False, name) if event is None: return False # 等这个 Event wv = win32event.WaitForSingleObject(event, timeout) CloseHandle(event) if wv == 0: return True else: return False
def OpenNameEventSet(name, loop=1): # print("open event = [" + name + "]") event = None for i in range(0, loop): # 打开 event = win32event.OpenEvent(0x1F0003, False, name) if event is not None: break # 打不开就sleep 然后再打开 Sleep(500) if event is None: return False win32event.SetEvent(event) CloseHandle(event) return True
def get_serial_ports(): success = False ports = [] global wmi # try WMI first try: if wmi is None: wmi = win32com.client.GetObject('winmgmts:') for port in wmi.InstancesOf('Win32_SerialPort'): ports.append((port.DeviceID, port.Name, '')) success = True except: pass if success: return ports ports = [] # fallback to simple filename probing, if WMI fails for i in range(1, 256): # FIXME: get friendly names name = 'COM%u' % i try: hFile = CreateFile( '\\\\.\\' + name, win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0, None, win32con.OPEN_EXISTING, 0, None) CloseHandle(hFile) ports.append((name, name, name)) except pywintypes.error as e: if e[0] in [ winerror.ERROR_ACCESS_DENIED, winerror.ERROR_GEN_FAILURE, winerror.ERROR_SHARING_VIOLATION, winerror.ERROR_SEM_TIMEOUT ]: ports.append((name, name, name)) return ports
def kill_scdaemon(): killed = False try: # Works for Windows. from win32com.client import GetObject from win32api import OpenProcess, CloseHandle, TerminateProcess wmi = GetObject('winmgmts:') ps = wmi.InstancesOf('Win32_Process') for p in ps: if p.Properties_('Name').Value == 'scdaemon.exe': pid = p.Properties_('ProcessID').Value handle = OpenProcess(1, False, pid) TerminateProcess(handle, -1) CloseHandle(handle) killed = True except ImportError: # Works for Linux and OS X. return_code = subprocess.call( # nosec ['/usr/bin/pkill', '-9', 'scdaemon']) if return_code == 0: killed = True if killed: time.sleep(0.1) return killed
def __del__(self): if self.mutex: CloseHandle(self.mutex)
def CloseHandle(self): # 一定要记得释放资源 CloseHandle(self.hProcess) # 因为这里还要调用原始的hProcess类型去关闭进程句柄,所以我们没有一开始对self.hProcess直接转换成int
import array # Get the ReadProcessMemory function ReadProcessMemory = windll.kernel32.ReadProcessMemory # Constants CONNECTION_PTR_OFFSET = 0x01139F94 SESSIONKEY_OFFSET = 0x508 SESSIONKEY_LENGTH = 40 # Adjust current process privileges hToken = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY) luid = LookupPrivilegeValue(None, SE_DEBUG_NAME) AdjustTokenPrivileges(hToken, False, [(luid, SE_PRIVILEGE_ENABLED)]) CloseHandle(hToken) # Get an handle on wow windowHandle = FindWindow(None, 'World of Warcraft') if not windowHandle: print('ERROR : Unable to find WoW window') sys.exit(0) threadID, processID = GetWindowThreadProcessId(windowHandle) wowHandle = OpenProcess(PROCESS_VM_READ, False, processID) # Get a pointer to the sessionkey lpBuffer = c_ulong() nSize = 4 lpNumberOfBytesRead = c_long(0) if not ReadProcessMemory(wowHandle.handle, CONNECTION_PTR_OFFSET,
def stop(self): """stop current actor""" super(WinFileSysMonitor, self).stop() for watch in self.watchList: CloseHandle(watch['handle']) self.watchList.remove(watch)
def __del__(self): self.session.release() CloseHandle(self.event)
def _win_mutex_destroy(self): ''' Esto es necesario para quitar el Mutex en win32 ''' from win32api import CloseHandle CloseHandle(self.mutex)
def __del__(self): from win32api import CloseHandle if self.mutex: CloseHandle(self.mutex)
def __del__(self): if os.name == 'nt': if self and self.mutex: CloseHandle(self.mutex)