Python win32file.OPEN_EXISTING Examples
The following are 21
code examples of win32file.OPEN_EXISTING().
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: test_win32file.py From ironpython2 with Apache License 2.0 | 8 votes |
def testSimpleFiles(self): try: fd, filename = tempfile.mkstemp() except AttributeError: self.fail("This test requires Python 2.3 or later") os.close(fd) os.unlink(filename) handle = win32file.CreateFile(filename, win32file.GENERIC_WRITE, 0, None, win32con.CREATE_NEW, 0, None) test_data = str2bytes("Hello\0there") try: win32file.WriteFile(handle, test_data) handle.Close() # Try and open for read handle = win32file.CreateFile(filename, win32file.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None) rc, data = win32file.ReadFile(handle, 1024) self.assertEquals(data, test_data) finally: handle.Close() try: os.unlink(filename) except os.error: pass # A simple test using normal read/write operations.
Example #2
Source File: win32.py From rekall with GNU General Public License v2.0 | 6 votes |
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 |
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: dump.py From Fastir_Collector with GNU General Public License v3.0 | 6 votes |
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 #5
Source File: test_win32file.py From ironpython2 with Apache License 2.0 | 6 votes |
def setUp(self): self.watcher_threads = [] self.watcher_thread_changes = [] self.dir_names = [] self.dir_handles = [] for i in range(self.num_test_dirs): td = tempfile.mktemp("-test-directory-changes-%d" % i) os.mkdir(td) self.dir_names.append(td) hdir = win32file.CreateFile(td, ntsecuritycon.FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ, None, # security desc win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS | win32con.FILE_FLAG_OVERLAPPED, None) self.dir_handles.append(hdir) changes = [] t = threading.Thread(target=self._watcherThreadOverlapped, args=(td, hdir, changes)) t.start() self.watcher_threads.append(t) self.watcher_thread_changes.append(changes)
Example #6
Source File: virtio_console_guest.py From avocado-vt with GNU General Public License v2.0 | 6 votes |
def open(self, name): """ Direct open devices. :param name: Port name. :return: 0 on success """ path = self.ports[name]['path'] try: self.files[path] = win32file.CreateFile(path, win32file.GENERIC_WRITE | win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None) except win32file.error as exc_detail: print("%s\nFAIL: Failed open file %s" % (str(exc_detail), name)) return exc_detail print("PASS: All files opened correctly.")
Example #7
Source File: platform_windows.py From scalyr-agent-2 with Apache License 2.0 | 6 votes |
def connect(self): """Attempts to connect to the server, but does not block. @return: True if the channel is now connected. @rtype: bool """ try: if win32pipe.WaitNamedPipe(self.__full_pipe_name, 10) != 0: self.__pipe_handle = win32file.CreateFile( self.__full_pipe_name, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, 0, None, ) return True else: return False except pywintypes.error as e: if e[0] == winerror.ERROR_FILE_NOT_FOUND: return False else: raise e
Example #8
Source File: WindowsServer.py From pycopia with Apache License 2.0 | 6 votes |
def CreateFile(self, fname, mode="r", bufsize=-1): "Open a file the same way a File Directory migration engine would." fname = cygwin2nt(fname) UserLog.msg("CreateFile", fname) if mode == "r": wmode = win32file.GENERIC_READ elif mode == "w": wmode = win32file.GENERIC_WRITE elif mode in ( 'r+', 'w+', 'a+'): wmode = win32file.GENERIC_READ | win32file.GENERIC_WRITE else: raise ValueError, "invalid file mode" h = win32file.CreateFile( fname, # CTSTR lpFileName, wmode, # DWORD dwDesiredAccess, win32file.FILE_SHARE_DELETE | win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, # DWORD dwShareMode, None, # LPSECURITY_ATTRIBUTES lpSecurityAttributes, win32file.OPEN_EXISTING, # DWORD dwCreationDisposition, win32file.FILE_ATTRIBUTE_NORMAL, # DWORD dwFlagsAndAttributes, 0, # HANDLE hTemplateFile ) self._files[int(h)] = h return int(h)
Example #9
Source File: __init__.py From EventGhost with GNU General Public License v2.0 | 5 votes |
def Connect(self): """ This function tries to connect to the named pipe from AlternateMceIrService. If it can't connect, it will periodically retry until the plugin is stopped or the connection is made. """ self.connecting = True #eg.PrintNotice("MCE_Vista: Connect started") while self.file is None and self.keepRunning: self.SetReceiving(False) try: self.file = win32file.CreateFile(r'\\.\pipe\MceIr',win32file.GENERIC_READ |win32file.GENERIC_WRITE,0,None, win32file.OPEN_EXISTING,win32file.FILE_ATTRIBUTE_NORMAL |win32file.FILE_FLAG_OVERLAPPED,None) if self.sentMessageOnce: eg.PrintNotice("MCE_Vista: Connected to MceIr pipe, started handling IR events") self.plugin.TriggerEvent("Connected") self.sentMessageOnce = False except: if not self.sentMessageOnce: eg.PrintNotice("MCE_Vista: MceIr pipe is not available, app doesn't seem to be running") eg.PrintNotice(" Will continue to try to connect to MceIr") eg.PrintNotice(" Message = %s"%win32api.FormatMessage(win32api.GetLastError())) self.plugin.TriggerEvent("Disconnected") self.sentMessageOnce = True #if self.service and IsServiceStopped(self.service): # eg.PrintNotice("MCE_Vista: MceIr service is stopped, trying to start it...") # StartService(self.service) time.sleep(1) self.connecting = False return
Example #10
Source File: utils.py From Fastir_Collector with GNU General Public License v3.0 | 5 votes |
def is_open(filename): handle = win32file.CreateFile(filename, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, 0) if handle: return True else: return False
Example #11
Source File: utils_rawstring.py From Fastir_Collector with GNU General Public License v3.0 | 5 votes |
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 #12
Source File: artifact_extractor.py From ArtifactExtractor with Apache License 2.0 | 5 votes |
def _preserve_timestamps(file_entry, output_path): """Obtain and set (to preserve) original timestamps of exported files.""" stat_object = file_entry.GetStat() if os.name == WINDOWS_IDENTIFIER: accessed = created = modified = dt.now() if stat_object.atime: if stat_object.atime_nano: accessed = dt.fromtimestamp((float(str(stat_object.atime) + '.' + str(stat_object.atime_nano)))) else: accessed = dt.fromtimestamp(stat_object.atime) if stat_object.crtime: if stat_object.crtime_nano: created = dt.fromtimestamp((float(str(stat_object.crtime) + '.' + str(stat_object.crtime_nano)))) else: created = dt.fromtimestamp(stat_object.crtime) if stat_object.mtime: if stat_object.mtime_nano: modified = dt.fromtimestamp((float(str(stat_object.mtime) + '.' + str(stat_object.mtime_nano)))) else: modified = dt.fromtimestamp(stat_object.mtime) handle = CreateFileW(output_path, GENERIC_WRITE, FILE_SHARE_WRITE, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None) SetFileTime(handle, created, accessed, modified) # does not seem to preserve nano precision of timestamps CloseHandle(handle) else: os.utime(output_path, (stat_object.atime, stat_object.mtime))
Example #13
Source File: npipesocket.py From deepWordBug with Apache License 2.0 | 5 votes |
def connect(self, address): win32pipe.WaitNamedPipe(address, self._timeout) try: handle = win32file.CreateFile( address, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, cSECURITY_ANONYMOUS | cSECURITY_SQOS_PRESENT, 0 ) except win32pipe.error as e: # See Remarks: # https://msdn.microsoft.com/en-us/library/aa365800.aspx if e.winerror == cERROR_PIPE_BUSY: # Another program or thread has grabbed our pipe instance # before we got to it. Wait for availability and attempt to # connect again. win32pipe.WaitNamedPipe(address, RETRY_WAIT_TIMEOUT) return self.connect(address) raise e self.flags = win32pipe.GetNamedPipeInfo(handle)[0] self._handle = handle self._address = address
Example #14
Source File: controller.py From libmelee with GNU Lesser General Public License v3.0 | 5 votes |
def connect(self): """Connect the controller to the console NOTE: Blocks until the other side is ready """ if self._is_dolphin: if platform.system() == "Windows": # "Create File" in windows is what you use to open a file. Not # create one. Because the windows API is stupid. self.pipe = win32file.CreateFile( self.pipe_path, win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None ) else: self.pipe = open(self.pipe_path, "w") return True else: # Remove any extra garbage that might have accumulated in the buffer self.tastm32.reset_input_buffer() # Send reset command self.tastm32.write(b'R') cmd = self.tastm32.read(2) if cmd != b'\x01R': # TODO Better error handling logic here print("ERROR: TAStm32 did not reset properly. Try power cycling it.") return False # Set to gamecube mode self.tastm32.write(b'SAG\x80\x00') cmd = self.tastm32.read(2) self.tastm32.reset_input_buffer() if cmd != b'\x01S': # TODO Better error handling logic here print("ERROR: TAStm32 did not set to GCN mode. Try power cycling it.") return False return True
Example #15
Source File: mpv.py From trakt-scrobbler with GNU General Public License v2.0 | 5 votes |
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 #16
Source File: test_win32file.py From ironpython2 with Apache License 2.0 | 5 votes |
def testSimpleOverlapped(self): # Create a file in the %TEMP% directory. import win32event testName = os.path.join( win32api.GetTempPath(), "win32filetest.dat" ) desiredAccess = win32file.GENERIC_WRITE overlapped = pywintypes.OVERLAPPED() evt = win32event.CreateEvent(None, 0, 0, None) overlapped.hEvent = evt # Create the file and write shit-loads of data to it. h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.CREATE_ALWAYS, 0, 0) chunk_data = str2bytes("z") * 0x8000 num_loops = 512 expected_size = num_loops * len(chunk_data) for i in range(num_loops): win32file.WriteFile(h, chunk_data, overlapped) win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE) overlapped.Offset = overlapped.Offset + len(chunk_data) h.Close() # Now read the data back overlapped overlapped = pywintypes.OVERLAPPED() evt = win32event.CreateEvent(None, 0, 0, None) overlapped.hEvent = evt desiredAccess = win32file.GENERIC_READ h = win32file.CreateFile( testName, desiredAccess, 0, None, win32file.OPEN_EXISTING, 0, 0) buffer = win32file.AllocateReadBuffer(0xFFFF) while 1: try: hr, data = win32file.ReadFile(h, buffer, overlapped) win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE) overlapped.Offset = overlapped.Offset + len(data) if not data is buffer: self.fail("Unexpected result from ReadFile - should be the same buffer we passed it") except win32api.error: break h.Close()
Example #17
Source File: virtio_console_guest.py From avocado-vt with GNU General Public License v2.0 | 4 votes |
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.")
Example #18
Source File: test_win32file.py From ironpython2 with Apache License 2.0 | 4 votes |
def testFileTimes(self): if issubclass(pywintypes.TimeType, datetime.datetime): from win32timezone import TimeZoneInfo now = datetime.datetime.now(tz=TimeZoneInfo.local()) nowish = now + datetime.timedelta(seconds=1) later = now + datetime.timedelta(seconds=120) else: rc, tzi = win32api.GetTimeZoneInformation() bias = tzi[0] if rc==2: # daylight-savings is in effect. bias += tzi[-1] bias *= 60 # minutes to seconds... tick = int(time.time()) now = pywintypes.Time(tick+bias) nowish = pywintypes.Time(tick+bias+1) later = pywintypes.Time(tick+bias+120) filename = tempfile.mktemp("-testFileTimes") # Windows docs the 'last time' isn't valid until the last write # handle is closed - so create the file, then re-open it to check. open(filename,"w").close() f = win32file.CreateFile(filename, win32file.GENERIC_READ|win32file.GENERIC_WRITE, 0, None, win32con.OPEN_EXISTING, 0, None) try: ct, at, wt = win32file.GetFileTime(f) self.failUnless(ct >= now, "File was created in the past - now=%s, created=%s" % (now, ct)) self.failUnless( now <= ct <= nowish, (now, ct)) self.failUnless(wt >= now, "File was written-to in the past now=%s, written=%s" % (now,wt)) self.failUnless( now <= wt <= nowish, (now, wt)) # Now set the times. win32file.SetFileTime(f, later, later, later) # Get them back. ct, at, wt = win32file.GetFileTime(f) # XXX - the builtin PyTime type appears to be out by a dst offset. # just ignore that type here... if issubclass(pywintypes.TimeType, datetime.datetime): self.failUnlessEqual(ct, later) self.failUnlessEqual(at, later) self.failUnlessEqual(wt, later) finally: f.Close() os.unlink(filename)
Example #19
Source File: tun-ping-responder.py From pyvpn with The Unlicense | 4 votes |
def openTunTap(): ''' \brief Open a TUN/TAP interface and switch it to TUN mode. \return The handler of the interface, which can be used for later read/write operations. ''' # retrieve the ComponentId from the TUN/TAP interface componentId = get_tuntap_ComponentId() print('componentId = {0}'.format(componentId)) # create a win32file for manipulating the TUN/TAP interface tuntap = win32file.CreateFile( r'\\.\Global\%s.tap' % componentId, win32file.GENERIC_READ | win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_SYSTEM | win32file.FILE_FLAG_OVERLAPPED, None ) print('tuntap = {0}'.format(tuntap.handle)) # have Windows consider the interface now connected win32file.DeviceIoControl( tuntap, TAP_IOCTL_SET_MEDIA_STATUS, '\x00\x00\x00\x00', None ) # prepare the parameter passed to the TAP_IOCTL_CONFIG_TUN commmand. # This needs to be a 12-character long string representing # - the tun interface's IPv4 address (4 characters) # - the tun interface's IPv4 network address (4 characters) # - the tun interface's IPv4 network mask (4 characters) configTunParam = [] configTunParam += TUN_IPv4_ADDRESS configTunParam += TUN_IPv4_NETWORK configTunParam += TUN_IPv4_NETMASK configTunParam = ''.join([chr(b) for b in configTunParam]) # switch to TUN mode (by default the interface runs in TAP mode) win32file.DeviceIoControl( tuntap, TAP_IOCTL_CONFIG_TUN, configTunParam, None ) # return the handler of the TUN interface return tuntap #=== misc
Example #20
Source File: win32pmem.py From volatility with GNU General Public License v2.0 | 4 votes |
def __init__(self, base, config, **kwargs): self.as_assert(base == None, 'Must be first Address Space') addrspace.AbstractRunBasedMemory.__init__(self, base, config, **kwargs) self.fhandle = 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) self.ParseMemoryRuns()
Example #21
Source File: interface.py From XFLTReaT with MIT License | 4 votes |
def win_tun_alloc(self, dev, flags): TAP_IOCTL_SET_MEDIA_STATUS = self.WIN_TAP_CONTROL_CODE(6, 0) import pywintypes guid = self.WIN_get_device_guid() if not guid: common.internal_print("Please install OpenVPN's Windows TAP driver (NDIS 6) to use XFLTReaT\r\nhttps://openvpn.net/index.php/open-source/downloads.html", -1) sys.exit(-1) # create a win32file for manipulating the TUN/TAP interface try: self.wintun = win32file.CreateFile("\\\\.\\Global\\{0}.tap".format(guid), win32file.GENERIC_READ | win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_SYSTEM | win32file.FILE_FLAG_NO_BUFFERING | win32file.FILE_FLAG_OVERLAPPED, None) except pywintypes.error as e: if e.args[0] == 31: # A device attached to the system is not functioning. common.internal_print("The TUN device is already in use. Maybe another XFLTReaT is running.", -1) sys.exit(-1) # have Windows consider the interface now connected win32file.DeviceIoControl(self.wintun, TAP_IOCTL_SET_MEDIA_STATUS, '\x01\x00\x00\x00', 1, None) return self.wintun