예제 #1
0
 def testFileTimesTimezones(self):
     if not issubclass(pywintypes.TimeType, datetime.datetime):
         # maybe should report 'skipped', but that's not quite right as
         # there is nothing you can do to avoid it being skipped!
         return
     filename = tempfile.mktemp("-testFileTimes")
     now_utc = win32timezone.utcnow()
     now_local = now_utc.astimezone(win32timezone.TimeZoneInfo.local())
     h = win32file.CreateFile(
         filename, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0,
         None, win32file.CREATE_ALWAYS, 0, 0)
     try:
         win32file.SetFileTime(h, now_utc, now_utc, now_utc)
         ct, at, wt = win32file.GetFileTime(h)
         self.failUnlessEqual(now_local, ct)
         self.failUnlessEqual(now_local, at)
         self.failUnlessEqual(now_local, wt)
         # and the reverse - set local, check against utc
         win32file.SetFileTime(h, now_local, now_local, now_local)
         ct, at, wt = win32file.GetFileTime(h)
         self.failUnlessEqual(now_utc, ct)
         self.failUnlessEqual(now_utc, at)
         self.failUnlessEqual(now_utc, wt)
     finally:
         h.close()
         os.unlink(filename)
예제 #2
0
 def testFileTimesTimezones(self):
     filename = tempfile.mktemp("-testFileTimes")
     # now() is always returning a timestamp with microseconds but the
     # file APIs all have zero microseconds, so some comparisons fail.
     now_utc = win32timezone.utcnow().replace(microsecond=0)
     now_local = now_utc.astimezone(win32timezone.TimeZoneInfo.local())
     h = win32file.CreateFile(
         filename,
         win32file.GENERIC_READ | win32file.GENERIC_WRITE,
         0,
         None,
         win32file.CREATE_ALWAYS,
         0,
         0,
     )
     try:
         win32file.SetFileTime(h, now_utc, now_utc, now_utc)
         ct, at, wt = win32file.GetFileTime(h)
         self.failUnlessEqual(now_local, ct)
         self.failUnlessEqual(now_local, at)
         self.failUnlessEqual(now_local, wt)
         # and the reverse - set local, check against utc
         win32file.SetFileTime(h, now_local, now_local, now_local)
         ct, at, wt = win32file.GetFileTime(h)
         self.failUnlessEqual(now_utc, ct)
         self.failUnlessEqual(now_utc, at)
         self.failUnlessEqual(now_utc, wt)
     finally:
         h.close()
         os.unlink(filename)
예제 #3
0
    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.assertTrue(
                ct >= now, "File was created in the past - now=%s, created=%s" %
                (now, ct))
            self.assertTrue(now <= ct <= nowish, (now, ct))
            self.assertTrue(
                wt >= now, "File was written-to in the past now=%s, written=%s" %
                (now, wt))
            self.assertTrue(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.assertEqual(ct, later)
                self.assertEqual(at, later)
                self.assertEqual(wt, later)

        finally:
            f.Close()
            os.unlink(filename)
예제 #4
0
    def testFileTimes(self):
        from win32timezone import TimeZoneInfo

        # now() is always returning a timestamp with microseconds but the
        # file APIs all have zero microseconds, so some comparisons fail.
        now = datetime.datetime.now(tz=TimeZoneInfo.utc()).replace(
            microsecond=0)
        nowish = now + datetime.timedelta(seconds=1)
        later = now + datetime.timedelta(seconds=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, UTCTimes=True)
            # 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...
            self.failUnlessEqual(ct, later)
            self.failUnlessEqual(at, later)
            self.failUnlessEqual(wt, later)

        finally:
            f.Close()
            os.unlink(filename)
예제 #5
0
def copy_file_time(source, destination):
    if os.name == 'nt':
        src_file = win32file.CreateFile(source, win32file.GENERIC_READ, 0,
                                        None, win32file.OPEN_EXISTING,
                                        win32con.FILE_ATTRIBUTE_NORMAL, 0)
        ct, at, wt = win32file.GetFileTime(src_file)
        src_file.close()
        dst_file = win32file.CreateFile(
            destination, win32file.GENERIC_READ | win32con.GENERIC_WRITE, 0,
            None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
        win32file.SetFileTime(dst_file, ct, at, wt)
        dst_file.close()
예제 #6
0
    def testFileBasicInfo(self):
        attr = win32file.GetFileAttributes(self.__filename)
        f = win32file.CreateFile(self.__filename, win32file.GENERIC_READ, 0, None,
                                 win32con.OPEN_EXISTING, 0, None)
        self.__handle = f
        ct, at, wt = win32file.GetFileTime(f)

        # bug #752: this throws ERROR_BAD_LENGTH (24) in x86 binaries of build 221
        basic_info = win32file.GetFileInformationByHandleEx(f, win32file.FileBasicInfo)

        self.assertEqual(ct, basic_info['CreationTime'])
        self.assertEqual(at, basic_info['LastAccessTime'])
        self.assertEqual(wt, basic_info['LastWriteTime'])
        self.assertEqual(attr, basic_info['FileAttributes'])
예제 #7
0
def get_file_times(filename):
    try:
        handle = win32file.CreateFile(path, win32file.GENERIC_READ, \
            win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, \
            None, win32file.OPEN_EXISTING, win32file.FILE_FLAG_BACKUP_SEMANTICS, None)
        times = win32file.GetFileTime(handle)
        win32file.CloseHandle(handle)
        return {
            'creation': pydatetime_to_str(times[0]),
            'access': pydatetime_to_str(times[1]),
            'modification': pydatetime_to_str(times[2])
        }
    except Exception as e:
        print(f'Failed to get file times {e}')
        return {}
예제 #8
0
def getFileCreationTime(fname):
    wintime1 = pywintypes.Time(0)
    wintime2 = pywintypes.Time(0)
    wintime3 = pywintypes.Time(0)
    winfile = win32file.CreateFile(
        fname, win32con.GENERIC_WRITE, win32con.FILE_SHARE_READ
        | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE, None,
        win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)

    wintime1, wintime2, wintime3 = win32file.GetFileTime(winfile)

    winfile.close()

    print hex(int(wintime1))[2:].decode('hex')
    print hex(int(wintime2))[2:].decode('hex')
    print hex(int(wintime3))[2:].decode('hex')
예제 #9
0
    def FileCopy(self, szSrc, szDest, pProgress, nOffset):
        bRes = false

        #ifdef __WXMSW__
        #szSrc = 'c:\\test.DAT'
        #szDest = 'c:\\neu\\AVG6DB_F.DAT'
        #print szSrc, szDest

        ### check if the source file really can be opened

        #TOMAKEBETTER: ask, if file exists or catch 'file not exist exception'
        bopend = True
        try:
            nSrcFile = open(szSrc, 'rb', 0)
        except:
            bopend = False
        #nSrcFile = _open(szSrc, _O_BINARY|_O_RDONLY, 0);
        #if(nSrcFile > -1):
        if bopend:
            #//if the destination file exists and is read-only

            ### check if the destination file already exists
            bopend = True
            try:
                nSrcFile = open(szDest, 'rb', 0)
            except:
                bopend = False
            if bopend:
                #if(0 == access(szDest, 00))
                dwAttr = win32file.GetFileAttributes(szDest)
                if (-1 != dwAttr
                        and dwAttr & win32con.FILE_ATTRIBUTE_READONLY):
                    #//remove read only flag
                    dwAttr &= ~(win32con.FILE_ATTRIBUTE_READONLY)
                    win32file.SetFileAttributes(szDest, dwAttr)

            #//TOFIX _O_RDWR instead of _O_RDONLY for rollback segment checking
            #nDstFile = open(szDest, _O_BINARY|_O_CREAT|_O_WRONLY, _S_IREAD);
            nDstFile = open(szDest, 'wb')

            ### check if the nDstFile can be created

            #if(nDstFile > -1)
            #
            if (nDstFile != -1):
                #char szBuffer[10000];
                nRead = 0

                #struct _stati64 st;
                #_stati64(szSrc, &st);
                #uSrcSize = 0
                uSrcSize = os.path.getsize(szSrc)
                #wxInt64 uSrcSize = st.st_size;  //__int64
                #_stati64(szDest, &st);
                #wxInt64 uDstSize = st.st_size;
                uDstSize = 0

                #TOMAKEBETTER: find better solution
                #//TOFIX implement overlapping resuming for content checking
                #if(nOffset>0 && uSrcSize > uDstSize){
                if nOffset > 0 and uSrcSize > uDstSize:
                    nSrcFile.seek(nSrcFile, uDstSize, 0)  #SEEK_SET)
                    nStartProgress = uDstSize
                nStartProgress = 0

                if (NULL != pProgress):
                    pProgress.InitCurrentFiles(szSrc, szDest)
                    pProgress.InitCurrentProgress(nStartProgress, uSrcSize)

                #i = 0
                while nRead < uSrcSize:
                    #print nRead, uSrcSize
                    szBuffer = nSrcFile.read(1000000)
                    #szBuffer = os.read (1000000)
                    nReaded = len(szBuffer)
                    #i += 1
                    if szBuffer == '':
                        break
                    if (NULL != pProgress):
                        if pProgress.IsAborted():
                            break
                        nRead += nReaded
                        #sleeptime = (random() * 2) + 0.5
                        #time.sleep(sleeptime/4)

                        pProgress.StepPos(nReaded)
                    #nDstFile.write (szBuffer, 10000)
                    #time.sleep(0.1)
                    nDstFile.write(szBuffer)

                #//TOFIX what if user wants to keep partialy copied file ? (option?)
                if (pProgress and pProgress.IsAborted()):
                    #//TOFIX reuse code common with Delete() -> version without Dlgs
                    nDstFile.close()
                    dwAttr = win32file.GetFileAttributes(szDest)
                    if (-1 != dwAttr
                            and dwAttr & win32con.FILE_ATTRIBUTE_READONLY):
                        #//remove read-only style (so delete API won't fail)
                        dwAttr &= ~(win32con.FILE_ATTRIBUTE_READONLY)
                        win32file.SetFileAttributes(szDest, dwAttr)
                    #//VERIFY
                    os.remove(szDest)
                else:
                    #//copy file attributes
                    dwAttrib = win32file.GetFileAttributes(szSrc)
                    #if(-1 != dwAttrib):
                    #    win32file.SetFileAttributes(szDest, dwAttrib)

                    #//before closing the file copy file dates
                    #FILETIME ftCreated, ftAccessed, ftModified;
                    #HANDLE hSrc = (HANDLE)_get_osfhandle(nSrcFile);
                    #HANDLE hDst = (HANDLE)_get_osfhandle(nDstFile);

                    nDstFile.close()
                    nSrcFile.close()
                    #print 'SetFileTime'
                    #hSrc = win32file.CreateFile(nSrcFile,  win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, 0, 0)
                    hSrc = win32file.CreateFile(szSrc, win32file.GENERIC_READ,
                                                0, None,
                                                win32file.OPEN_EXISTING, 0, 0)
                    #TOMAKEBETTER: better solution

                    try:
                        hDst = win32file.CreateFile(szDest,
                                                    win32file.GENERIC_WRITE, 0,
                                                    None,
                                                    win32file.OPEN_EXISTING, 0,
                                                    0)
                        filetime = win32file.GetFileTime(hSrc)
                        if (filetime):
                            win32file.SetFileTime(hDst, filetime[1],
                                                  filetime[2], filetime[3])
                        hDst.Close()
                    except:
                        wxMessageBox(_("cannot access to destination file!"))
                    #erst hier, sonst kam bei filetime von read only 'cannot access to destination file!'
                    if (-1 != dwAttrib):
                        win32file.SetFileAttributes(szDest, dwAttrib)

                    #[1, <PyTime:05.08.2003 21:12:20>, <PyTime:09.01.2004 23:00:00>, <PyTime:10.01.2004 18:28:40>]
                    hSrc.Close()
                    #if(GetFileTime(hSrc, &ftCreated, &ftAccessed, &ftModified))
                    #    SetFileTime(hDst, &ftCreated, &ftAccessed, &ftModified);

                bRes = True

            nSrcFile.close()
        #else
        '''
        //TOFIX add missing code
        int nSrcFile = open(szSrc, O_RDONLY, 0);
        if(nSrcFile > -1)
        {
            //if the destination file exists and is read-only
            if(0 == access(szDest, 00)){
            }

            //TOFIX O_RDWR instead of O_RDONLY for rollback segment checking
            int nDstFile = open(szDest, O_CREAT|O_WRONLY|O_LARGEFILE, S_IREAD);
            if(nDstFile > -1)
            {
                char szBuffer[10000];
                wxUint32 nRead;

            struct stat st;
            stat(szSrc, &st);
            wxInt64 uSrcSize = st.st_size;  //__int64
            stat(szDest, &st);
            wxInt64 uDstSize = st.st_size;

            wxInt64 nStartProgress = 0;

            //TOFIX implement overlapping resuming for content checking
            if(nOffset>0 && uSrcSize > uDstSize){
                lseek64(nSrcFile, uDstSize, SEEK_SET);
                nStartProgress = uDstSize;
            }

            if(NULL != pProgress){
                    pProgress->InitCurrentFiles(szSrc, szDest);
                    pProgress->InitCurrentProgress(nStartProgress, uSrcSize);
                }

                while(0 != (nRead = read(nSrcFile, szBuffer, sizeof(szBuffer))))
                {
                    if(NULL != pProgress){
                        if(pProgress->IsAborted())
                            break;
                        pProgress->StepPos(nRead);
                    }

                    write(nDstFile, szBuffer, nRead);
                }

                //TOFIX what if user wants this !!! (option)
                if(pProgress && pProgress->IsAborted())
                {
                    //delete file - including readonly file
                    //TOFIX reuse code common with Delete() -> version without Dlgs
                    ::wxRemoveFile(szDest);
                }
                else
                {
                    //copy file attributes
                }

                close(nDstFile);
                bRes = true;
            }

            close(nSrcFile);
        }

        #endif
        '''
        return bRes
예제 #10
0
    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)