Python win32file.CloseHandle() Examples

The following are 26 code examples of win32file.CloseHandle(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module win32file , or try the search function .
Example #1
Source File: __init__.py    From EventGhost with GNU General Public License v2.0 6 votes vote down vote up
def Stop(self):
        """
        This will be called to stop the thread.
        """
        if self.file:
            writeOvlap = win32file.OVERLAPPED()
            writeOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None)
            msg = "q".encode("ascii")
            win32file.WriteFile(self.file, msg, writeOvlap)
            win32file.CloseHandle(self.file)
            self.file = None
        self.keepRunning = False

        if self.service:
            win32service.CloseServiceHandle(self.service)

        #eg.PrintNotice("MCE_Vista: stopping thread") 
Example #2
Source File: win32.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def _OpenFileForRead(self, path):
        try:
            fhandle = self.fhandle = win32file.CreateFile(
                path,
                win32file.GENERIC_READ,
                win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
                None,
                win32file.OPEN_EXISTING,
                win32file.FILE_ATTRIBUTE_NORMAL,
                None)

            self._closer = weakref.ref(
                self, lambda x: win32file.CloseHandle(fhandle))

            self.write_enabled = False
            return fhandle

        except pywintypes.error as e:
            raise IOError("Unable to open %s: %s" % (path, e)) 
Example #3
Source File: win32.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def _OpenFileForWrite(self, path):
        try:
            fhandle = self.fhandle = win32file.CreateFile(
                path,
                win32file.GENERIC_READ | win32file.GENERIC_WRITE,
                win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
                None,
                win32file.OPEN_EXISTING,
                win32file.FILE_ATTRIBUTE_NORMAL,
                None)
            self.write_enabled = True
            self._closer = weakref.ref(
                self, lambda x: win32file.CloseHandle(fhandle))

            return fhandle

        except pywintypes.error as e:
            raise IOError("Unable to open %s: %s" % (path, e)) 
Example #4
Source File: tun-ping-responder.py    From pyvpn with The Unlicense 6 votes vote down vote up
def main():
    
    #=== open the TUN/TAP interface
    
    tuntap = openTunTap()
    
    #=== start read/write threads
    
    writeThread = WriteThread(tuntap)
    readThread  = ReadThread(tuntap,writeThread.transmit)
    
    readThread.start()
    writeThread.start()
    
    #=== wait for Enter to stop
    
    raw_input("Press enter to stop...\n")
    
    readThread.close()
    writeThread.close()
    win32file.CloseHandle(tuntap) 
Example #5
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def testCompletionPortsMultiple(self):
        # Mainly checking that we can "associate" an existing handle.  This
        # failed in build 203.
        ioport = win32file.CreateIoCompletionPort(win32file.INVALID_HANDLE_VALUE,
                                                  0, 0, 0)
        socks = []
        for PORT in range(9123, 9125):
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            sock.bind(('', PORT))
            sock.listen(1)
            socks.append(sock)
            new = win32file.CreateIoCompletionPort(sock.fileno(), ioport, PORT, 0)
            assert new is ioport
        for s in socks:
            s.close()
        hv = int(ioport)
        ioport = new = None
        # The handle itself should be closed now (unless we leak references!)
        # Check that.
        try:
            win32file.CloseHandle(hv)
            raise RuntimeError("Expected close to fail!")
        except win32file.error, details:
            self.failUnlessEqual(details.winerror, winerror.ERROR_INVALID_HANDLE) 
Example #6
Source File: test_win32file.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _watcherThread(self, dn, dh, changes):
        # A synchronous version:
        # XXX - not used - I was having a whole lot of problems trying to
        # get this to work.  Specifically:
        # * ReadDirectoryChangesW without an OVERLAPPED blocks infinitely.
        # * If another thread attempts to close the handle while
        #   ReadDirectoryChangesW is waiting on it, the ::CloseHandle() method
        #   blocks (which has nothing to do with the GIL - it is correctly
        #   managed)
        # Which ends up with no way to kill the thread!
        flags = win32con.FILE_NOTIFY_CHANGE_FILE_NAME
        while 1:
            try:
                print "waiting", dh
                changes = win32file.ReadDirectoryChangesW(dh,
                                                          8192,
                                                          False, #sub-tree
                                                          flags)
                print "got", changes
            except:
                raise
            changes.extend(changes) 
Example #7
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 6 votes vote down vote up
def close(self, filepath):
        """
        Close open port.

        :param filepath: File to close.
        """
        hFile = None
        path = self.ports[filepath]["path"]
        if path is not None:
            if path in list(self.files.keys()):
                hFile = self.files[path]
                del self.files[path]
            if hFile is not None:
                try:
                    win32file.CloseHandle(hFile)
                except win32file.error as inst:
                    print("FAIL: Closing the file: " + str(inst))
                    return
        print("PASS: Close") 
Example #8
Source File: dump.py    From Fastir_Collector with GNU General Public License v3.0 6 votes vote down vote up
def csv_export_ram(self):
        """Dump ram using winpmem"""
        hSvc = create_driver_service(self.logger)
        start_service(hSvc, self.logger)
        try:
            fd = win32file.CreateFile(
                "\\\\.\\pmem",
                win32file.GENERIC_READ | win32file.GENERIC_WRITE,
                win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
                None,
                win32file.OPEN_EXISTING,
                win32file.FILE_ATTRIBUTE_NORMAL,
                None)
            try:
                t = time.time()
                image = _Image(fd)
                self.logger.info("Imaging to " + self.output_dir + '\\' + self.computer_name + '_memdump.raw')
                image.DumpWithRead(self.output_dir + '\\' + self.computer_name + '_memdump.raw')
                self.logger.info("Completed in %s seconds" % (time.time() - t))
            finally:
                win32file.CloseHandle(fd)
        finally:
            stop_and_delete_driver_service(hSvc) 
Example #9
Source File: mpv.py    From trakt-scrobbler with GNU General Public License v2.0 5 votes vote down vote up
def conn_loop(self):
        self.is_running = True
        self.update_vars()
        self.file_handle = win32file.CreateFile(
            self.ipc_path,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            0, None,
            win32file.OPEN_EXISTING,
            0, None
        )
        while self.is_running:
            try:
                while not self.write_queue.empty():
                    win32file.WriteFile(
                        self.file_handle, self.write_queue.get_nowait())
            except win32file.error:
                logger.debug('Exception while writing to pipe.', exc_info=True)
                self.is_running = False
                break
            size = win32file.GetFileSize(self.file_handle)
            if size > 0:
                while size > 0:
                    # pipe has data to read
                    _, data = win32file.ReadFile(self.file_handle, 4096)
                    self.on_data(data)
                    size = win32file.GetFileSize(self.file_handle)
            else:
                time.sleep(1)
        win32file.CloseHandle(self.file_handle)
        logger.debug('Pipe closed.') 
Example #10
Source File: win32pmem.py    From volatility with GNU General Public License v2.0 5 votes vote down vote up
def close(self):
        try:
            win32file.CloseHandle(self.fhandle)
        except AttributeError:
            pass 
Example #11
Source File: process.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def closeStdout(self):
        if hasattr(self, "hChildStdoutRd"):
            win32file.CloseHandle(self.hChildStdoutRd)
            del self.hChildStdoutRd
            self.closedStdout = True
            self.connectionLostNotify() 
Example #12
Source File: process.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def closeStderr(self):
        if hasattr(self, "hChildStderrRd"):
            win32file.CloseHandle(self.hChildStderrRd)
            del self.hChildStderrRd
            self.closedStderr = True
            self.connectionLostNotify() 
Example #13
Source File: process.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def _closeStdin(self):
        if hasattr(self, "hChildStdinWr"):
            win32file.CloseHandle(self.hChildStdinWr)
            del self.hChildStdinWr
            self.closingStdin = False
            self.closedStdin = True 
Example #14
Source File: NamedMutex.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def __del__(self):

        if os.name == 'nt':
            if self._mutex is not None:
                # Gotchas: Don't close the handle before releasing it or the
                # mutex won't release until the python script exits.  It's 
                # safe to call ReleaseMutex even if the local process hasn't 
                # acquired the mutex.  If this process doesn't have mutex then 
                # the call fails.  Note that in Windows, mutexes are literally 
                # per process.  Multiple mutexes created with the same name
                # from the same process will be treated as one with respect to 
                # release and acquire.
                self.release()

                # windows will destroy the mutex when the last handle to that
                # mutex is closed.
                win32file.CloseHandle(self._mutex)
                del self._mutex
   
        elif os.name == 'posix':
            if self._mylock:
                self.release()

            # relock file non-blocking to see if anyone else was 
            # waiting on it.  (A race condition exists where another process
            # could have just opened but not yet locked the file.  This process
            # then deletes the file.  When the other process resumes, the
            # flock call fails.  This is however not a particularly bad
            # race condition since acquire() simply repeats the open & flock.)
            if os.path.exists(self._path) and self.acquire(False):

                try:
                    os.remove(self._path)
                except:
                    pass

                flock( self._mutex.fileno(), fcntl.LOCK_UN )
                self._mutex.close() 
Example #15
Source File: _dumbwin32proc.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def maybeCallProcessEnded(self):
        if self.closedNotifies == 3 and self.lostProcess:
            win32file.CloseHandle(self.hProcess)
            win32file.CloseHandle(self.hThread)
            self.hProcess = None
            self.hThread = None
            BaseProcess.maybeCallProcessEnded(self)


    # IConsumer 
Example #16
Source File: utils_rawstring.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def get_physical_drive_size(drive="\\\\.\\PhysicalDrive0"):
    """Uses IOCTL to get physical drives size"""
    handle = win32file.CreateFile(drive, 0, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, 0)
    if handle:
        IOCTL_DISK_GET_DRIVE_GEOMETRY = 0x00070000
        info = win32file.DeviceIoControl(handle, IOCTL_DISK_GET_DRIVE_GEOMETRY, '', 24)
        win32file.CloseHandle(handle)
        if info:
            (cyl_lo, cyl_hi, media_type, tps, spt, bps) = struct.unpack('6L', info)
            mediasize = ((cyl_hi << 32) + cyl_lo) * tps * spt * bps
            """print mediasize, 'bytes'
            print mediasize/10**3, 'kbytes'
            print mediasize/10**6, 'Mbytes'
            print mediasize/10**9, 'Gbytes'"""
            return mediasize 
Example #17
Source File: platform_windows.py    From scalyr-agent-2 with Apache License 2.0 5 votes vote down vote up
def close(self):
            """Closes the channel to the server.
            """
            if self.__pipe_handle is not None:
                win32file.CloseHandle(self.__pipe_handle)
                self.__pipe_handle = None 
Example #18
Source File: _dumbwin32proc.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def maybeCallProcessEnded(self):
        if self.closedNotifies == 3 and self.lostProcess:
            win32file.CloseHandle(self.hProcess)
            win32file.CloseHandle(self.hThread)
            self.hProcess = None
            self.hThread = None
            BaseProcess.maybeCallProcessEnded(self)

    # IConsumer 
Example #19
Source File: _dumbwin32proc.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def maybeCallProcessEnded(self):
        if self.closedNotifies == 3 and self.lostProcess:
            win32file.CloseHandle(self.hProcess)
            win32file.CloseHandle(self.hThread)
            self.hProcess = None
            self.hThread = None
            BaseProcess.maybeCallProcessEnded(self)


    # IConsumer 
Example #20
Source File: win32.py    From multibootusb with GNU General Public License v2.0 5 votes vote down vote up
def _closeHandle(h):
    x = win32file.CloseHandle(h)
    assert x != win32file.INVALID_HANDLE_VALUE
    return x 
Example #21
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 5 votes vote down vote up
def exit_threads(self):
        """
        Function end all running data switch.
        """
        self.exit_thread.set()
        for th in self.threads:
            print("join")
            th.join()
        self.exit_thread.clear()

        del self.threads[:]
        for desc in six.itervalues(self.files):
            win32file.CloseHandle(desc)
        self.files.clear()
        print("PASS: All threads finished") 
Example #22
Source File: win32gui_devicenotify.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def OnDeviceChange(hwnd, msg, wp, lp):
    # Unpack the 'lp' into the appropriate DEV_BROADCAST_* structure,
    # using the self-identifying data inside the DEV_BROADCAST_HDR.
    info = win32gui_struct.UnpackDEV_BROADCAST(lp)
    print "Device change notification:", wp, str(info)
    if wp==win32con.DBT_DEVICEQUERYREMOVE and info.devicetype==win32con.DBT_DEVTYP_HANDLE:
        # Our handle is stored away in the structure - just close it
        print "Device being removed - closing handle"
        win32file.CloseHandle(info.handle)
        # and cancel our notifications - if it gets plugged back in we get
        # the same notification and try and close the same handle...
        win32gui.UnregisterDeviceNotification(info.hdevnotify)
    return True 
Example #23
Source File: win32.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def close(self):
        win32file.CloseHandle(self.fhandle) 
Example #24
Source File: packetselector.py    From XFLTReaT with MIT License 5 votes vote down vote up
def delete_client(self, client):
		if client in self.clients:

			if self.os_type == common.OS_WINDOWS:
				import win32file

				try:
					win32file.CloseHandle(client.get_pipe_r())
					win32file.CloseHandle(client.get_pipe_w())
				except Exception as e:
					common.internal_print("Remove authenticated client: CloseHandle exception: {0}".format(e), -1)
			else:
				try:
					client.get_pipe_r_fd().close()
					client.get_pipe_w_fd().close()
				except Exception as e:
					common.internal_print("Remove authenticated client: os.close exception: {0}".format(e), -1)

			client.call_stopfp()
			self.clients.remove(client)

		return

	# This function should run from the point when the framework was started.
	# It runs as an infinite loop to read the packets off the tunnel.
	# When an IPv4 packet was found that will be selected and checked whether
	# it addresses a client in the client list. If a client was found, then the
	# packet will be written on that pipe. 
Example #25
Source File: interface.py    From XFLTReaT with MIT License 5 votes vote down vote up
def win_close_tunnel(self, tun):
		try:
			win32file.CloseHandle(self.wintun)
		except:
			pass

		return 
Example #26
Source File: virtio_console_guest.py    From avocado-vt with GNU General Public License v2.0 4 votes vote down vote up
def init(self, in_files):
        """
        Init and check port properties.
        """
        # This only sets the ports names and paths
        # TODO: symlinks are sometimes missing, use /dev/vport%dp%d"
        self.ports = self._get_port_status(in_files)

        # Check if all ports really exists
        remove = []
        for item in six.iteritems(self.ports):
            port = item[1]
            try:
                hFile = win32file.CreateFile(port['path'], 0, 0, None,
                                             win32file.OPEN_EXISTING,
                                             win32file.FILE_ATTRIBUTE_NORMAL,
                                             None)
                win32file.CloseHandle(hFile)
            except win32file.error:
                remove.append(port['name'])
                print("Fail to open port %s" % port['name'])
        for name in remove:
            del(self.ports[name])

        # Check if in_files count and system port count matches
        # TODO: Not all devices are listed
        # TODO: Find the way to list all devices
        if remove:
            print("FAIL: Not all ports are present, check the log.")
            return
        """
        reg = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "System")
        reg = _winreg.OpenKey(reg, "CurrentControlSet")
        reg = _winreg.OpenKey(reg, "Services")
        reg = _winreg.OpenKey(reg, "VirtioSerial")
        reg = _winreg.OpenKey(reg, "Enum")
        virtio_port_count = _winreg.QueryValueEx(reg, "Count")[0]
        if virtio_port_count != len(self.ports):
            print("FAIL: Number of ports (%d) doesn't match the number"
                  " of ports in registry (%d)"
                  % (len(self.ports), virtio_port_count))
            return
        """

        print("PASS: Init and check virtioconsole files in system.")