def GetFileInformationByHandle(handle): """ Note that pywin32 FILETIME structure is buggy, and here nFileSizeHigh/nFileSizeLow return 0 on FAT32 whereas on ctypes backend they have a proper value. """ info = BY_HANDLE_FILE_INFORMATION() (info.dwFileAttributes, _ftCreationTime, _ftLastAccessTime, _ftLastWriteTime, info.dwVolumeSerialNumber, info.nFileSizeHigh, info.nFileSizeLow, info.nNumberOfLinks, info.nFileIndexHigh, info.nFileIndexLow) = win32file.GetFileInformationByHandle(handle) ##print(">>>>>>", info.__dict__) # to workaround bugs, we don't deal with "PyTime" objects, we fallback to stdlib... mystat = os.fstat(_open_osfhandle(handle, 0)) info.ftCreationTime = FILETIME( *_utilities.python_timestamp_to_win32_filetime(mystat.st_ctime)) info.ftLastAccessTime = FILETIME( *_utilities.python_timestamp_to_win32_filetime(mystat.st_atime)) info.ftLastWriteTime = FILETIME( *_utilities.python_timestamp_to_win32_filetime(mystat.st_mtime)) return info
def windows_nlinks(path): import win32file dwFlagsAndAttributes = win32file.FILE_FLAG_BACKUP_SEMANTICS if os.path.isdir(path) else 0 handle = win32file.CreateFile(path, win32file.GENERIC_READ, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, dwFlagsAndAttributes, None) try: return win32file.GetFileInformationByHandle(handle)[7] finally: handle.Close()
def get_fileid(x): if isbytestring(x): x = x.decode(filesystem_encoding) try: h = win32file.CreateFile(x, 0, 0, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_BACKUP_SEMANTICS, 0) handles.append(h) data = win32file.GetFileInformationByHandle(h) except (error, EnvironmentError): return None return (data[4], data[8], data[9])
def __init__(self, parent, fname): self.parent = parent with open(path.join(parent.folder, fname), "rb") as fp: handle = win32file._get_osfhandle(fp.fileno()) info = win32file.GetFileInformationByHandle(handle) uid = str((info[8] << 32) + info[9]) self.uid = uid self.info = self.parent.getInfoByUid(self.uid) or [0b0, fname, "", ""]
def nlinks(pathname): """Return number of hardlinks for the given file.""" try: fh = win32file.CreateFile(pathname, win32file.GENERIC_READ, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, None) res = win32file.GetFileInformationByHandle(fh) fh.Close() return res[7] except pywintypes.error: return os.lstat(pathname).st_nlink
def _getfileinfo(pathname): """Return number of hardlinks for the given file.""" try: fh = win32file.CreateFile(pathname, win32file.GENERIC_READ, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, None) try: return win32file.GetFileInformationByHandle(fh) finally: fh.Close() except pywintypes.error: return None
def _getfileinfo(pathname): """Return number of hardlinks for the given file.""" try: fh = win32file.CreateFile(pathname, win32file.GENERIC_READ, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, None) except pywintypes.error: raise OSError(errno.ENOENT, 'The system cannot find the file specified') try: return win32file.GetFileInformationByHandle(fh) finally: fh.Close()
def inodeForWin(self, file_path): """ File ID for NTFS Returns the complete file ID as a single long string (volume number, high index, low index) @param file_path: File Path @return: """ try: self.Fixity = SharedApp.SharedApp.App except: pass id_node = '' try: target = open(file_path, 'rb') except: try: target = open(file_path.decode('utf-8'), 'rb') except: self.Fixity.logger.LogException(Exception.message) pass pass try: id_node = str(win32file.GetFileInformationByHandle(win32file._get_osfhandle(target.fileno()))[4]) + \ str(win32file.GetFileInformationByHandle(win32file._get_osfhandle(target.fileno()))[8]) + \ str(win32file.GetFileInformationByHandle(win32file._get_osfhandle(target.fileno()))[9]) return id_node except: self.Fixity.logger.LogException(Exception.message) pass return id_node
def windows_get_fileid(path): ''' The fileid uniquely identifies actual file contents (it is the same for all hardlinks to a file). Similar to inode number on linux. ''' import win32file from pywintypes import error if isbytestring(path): path = path.decode(filesystem_encoding) try: h = win32file.CreateFileW(path, 0, 0, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_BACKUP_SEMANTICS, 0) try: data = win32file.GetFileInformationByHandle(h) finally: win32file.CloseHandle(h) except (error, EnvironmentError): return None return data[4], data[8], data[9]
def old_windows_get_fileid(path): # we dont use this anymore as the win32 implementation reads the windows # registry to convert file times which is slow and breaks on systems with # registry issues. import win32file from pywintypes import error if isbytestring(path): path = path.decode(filesystem_encoding) try: h = win32file.CreateFileW(path, 0, 0, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_BACKUP_SEMANTICS, 0) try: data = win32file.GetFileInformationByHandle(h) finally: win32file.CloseHandle(h) except (error, EnvironmentError): return None return data[4], data[8], data[9]
def _get_file_id_windows(filename, is_directory): """Get the data that identifies a windows file. This is done by returning a tuple containing the drive serial unmber, and two file indexes. """ try: hFile = win32file.CreateFile(filename, win32file.GENERIC_READ, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_BACKUP_SEMANTICS if is_directory else 0, None) try: _, _, _, _, dwVolumeSerialNumber, _, _, _, nFileIndexHigh, nFileIndexLow = \ win32file.GetFileInformationByHandle (hFile) return dwVolumeSerialNumber, nFileIndexHigh, nFileIndexLow finally: hFile.Close() except pywintypes.error as ex: raise Exception(repr(ex))
def get_file_information(path): # First windows API call handle = win32file.CreateFile( path, SYMBOLS.FILE_READ_ATTRIBUTES, SYMBOLS.FILE_SHARE_READ | SYMBOLS.FILE_SHARE_WRITE | SYMBOLS.FILE_SHARE_DELETE, None, SYMBOLS.OPEN_EXISTING, SYMBOLS.FILE_FLAG_OPEN_REPARSE_POINT | SYMBOLS.FILE_FLAG_BACKUP_SEMANTICS, 0, ) # Second windows API call assert handle != win32file.INVALID_HANDLE_VALUE file_info = win32file.GetFileInformationByHandle(handle) # Close the handle # This is necessary since we use a single process # for running all the commands from a single test case win32file.CloseHandle(handle) # Convert file info into a dictionary return file_info_to_dict(file_info)
def get_unique_id(hFile): (attributes, created_at, accessed_at, written_at, volume, file_hi, file_lo, n_links, index_hi, index_lo) = win32file.GetFileInformationByHandle(hFile) return volume, index_hi, index_lo
def process6(self): answer6 = 6 while answer6 != '10': print('1 - To get file attributes\n' '2 - To set file attributes\n' '3 - To get file information by handle\n' '4 - To get file time\n' '5 - To set file time\n' '10 - To exit to menu') answer6 = input() if answer6 == '1': # print(win32con.FILE_ATTRIBUTE_*) print("Enter the name of file to get file attributes\n") attr = win32api.GetFileAttributes(input()) attribute_encoder(attr) elif answer6 == '2': #print("Enter the name of file\n") #path = '' attr = 0 #ans = 0 path = input("Enter the name of file\n") ans = input("Файл или каталог - архивные?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_ARCHIVE ans = input("Файл или каталог сжатые?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_COMPRESSED ans = input("Зарезервировано, не используется?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_DEVICE ans = input("Дескриптор идентифицирует каталог?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_DIRECTORY ans = input("Файл или каталог - зашифрованные?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_ENCRYPTED ans = input("Файл или каталог скрытые?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_HIDDEN ans = input("Файл или каталог не имеют других установленных атрибутов?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_NORMAL ans = input("Файл не будет индексирован содержащим индексы модулем обслуживания?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_NOT_CONTENT_INDEXED ans = input("Данные файла доступны не сразу?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_OFFLINE ans = input("Файл или каталог только для чтения?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_READONLY ans = input("Файл или каталог имеет связанную точку повторной обработки?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_REPARSE_POINT ans = input("Файл - разреженный файл?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_SPARSE_FILE ans = input("Файл или каталог - используются операционной системой?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_SYSTEM ans = input("Файл используется для временного хранения?Y-да, иначе-нет") if ans == 'Y' or ans == 'y': attr += FILE_ATTRIBUTE_TEMPORARY win32api.SetFileAttributes(path, attr) elif answer6 == '3': print('Input path to file:') handle = win32file.CreateFile(input(), win32file.GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None) input() inf = win32file.GetFileInformationByHandle(handle) attribute_encoder(inf[0]) time_encoder(inf[1:4]) #print("Serial number: ", inf[4]) win32api.CloseHandle(handle) elif answer6 == '4': print('Input path to file:') handle = win32file.CreateFile(input(), win32file.GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None) time = win32file.GetFileTime(handle) #strftime("%a, %d %b %Y %H:%M:%S +0000", time[0]) time_encoder(time) win32api.CloseHandle(handle) elif answer6 == '5': print('Input path to file:') handle = win32file.CreateFile(input(), win32file.GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None) PyTIME = pywintypes.Time(localtime()) win32file.SetFileTime(handle, PyTIME, PyTIME, PyTIME, False) win32api.CloseHandle(handle)
def get_fileid(fh): info = win32file.GetFileInformationByHandle(fh) return sum(info[8:])