Ejemplo n.º 1
0
def NukeFolder(folder):
    username = win32api.GetUserName()
    print("NukeFolder Unsealing " + folder + " for " + username)
    Unseal(username, folder)
    print("[NukeFolder] starting os.walk on %s " % folder)
    for root, dirs, files in os.walk(folder, topdown=False):
        for name in dirs:
            print("[D] Dir found: " + os.path.join(root, name))
            try:
                win32api.SetFileAttributes(os.path.join(root, name),
                                           win32con.FILE_ATTRIBUTE_NORMAL)
                win32file.RemoveDirectory(os.path.join(root, name))
            except Exception as er:
                cprint("Exception on Removing Directory %s " %
                       os.path.join(root, name))
        for name in files:
            print("[F] Delete: %s " % os.path.join(root, name))
            win32file.DeleteFile(os.path.join(root, name))

    try:
        win32api.SetFileAttributes(folder, win32con.FILE_ATTRIBUTE_NORMAL)
        win32file.RemoveDirectory(folder)
    except Exception as er:
        cprint("NukeFolder Exception on Setting File Attributes %s on %s " %
               (type(er).__name__, folder))
Ejemplo n.º 2
0
    def testLongLongPathNames(self):
        # We need filename where the FQN is > 256 - simplest way is to create a
        # 250 character directory in the cwd (except - cwd may be on a drive
        # not supporting \\\\?\\ (eg, network share) - so use temp.
        import win32file
        basename = "a" * 250
        # but we need to ensure we use the 'long' version of the
        # temp dir for later comparison.
        long_temp_dir = win32api.GetLongPathNameW(tempfile.gettempdir())
        fname = "\\\\?\\" + os.path.join(long_temp_dir, basename)
        try:
            win32file.CreateDirectoryW(fname, None)
        except win32api.error as details:
            if details.winerror != winerror.ERROR_ALREADY_EXISTS:
                raise
        try:
            # GetFileAttributes automatically calls GetFileAttributesW when
            # passed unicode
            try:
                attr = win32api.GetFileAttributes(fname)
            except win32api.error as details:
                if details.winerror != winerror.ERROR_FILENAME_EXCED_RANGE:
                    raise

            attr = win32api.GetFileAttributes(str(fname))
            assert attr & win32con.FILE_ATTRIBUTE_DIRECTORY, attr

            long_name = win32api.GetLongPathNameW(fname)
            assert long_name.lower() == fname.lower()
        finally:
            win32file.RemoveDirectory(fname)
Ejemplo n.º 3
0
def _rmtree_windows(path):
    """ Windows-specific rmtree that handles path lengths longer than MAX_PATH.
        Ported from clobberer.py.
    """
    assert _is_windows()
    path = os.path.realpath(path)
    full_path = '\\\\?\\' + path
    if not os.path.exists(full_path):
        return
    if not PYWIN32:
        if not os.path.isdir(path):
            return run_cmd('del /F /Q "%s"' % path)
        else:
            return run_cmd('rmdir /S /Q "%s"' % path)
    # Make sure directory is writable
    win32file.SetFileAttributesW('\\\\?\\' + path,
                                 win32file.FILE_ATTRIBUTE_NORMAL)
    # Since we call rmtree() with a file, sometimes
    if not os.path.isdir('\\\\?\\' + path):
        return win32file.DeleteFile('\\\\?\\' + path)

    for ffrec in win32api.FindFiles('\\\\?\\' + path + '\\*.*'):
        file_attr = ffrec[0]
        name = ffrec[8]
        if name == '.' or name == '..':
            continue
        full_name = os.path.join(path, name)

        if file_attr & win32file.FILE_ATTRIBUTE_DIRECTORY:
            _rmtree_windows(full_name)
        else:
            win32file.SetFileAttributesW('\\\\?\\' + full_name,
                                         win32file.FILE_ATTRIBUTE_NORMAL)
            win32file.DeleteFile('\\\\?\\' + full_name)
    win32file.RemoveDirectory('\\\\?\\' + path)
Ejemplo n.º 4
0
    def _deleteFolderWin32(self, full_path):
        """A function like shutil.rmtree using win32api.

    The win32file apis must be used for this task on win32 platform
    because the win32 shell libs cannot handle file paths > 256 chars long.

    Args:
      full_path: Absolute path of the folder to recursively delete.
    """
        unicode_path = '\\\\?\\%s' % full_path
        folder_iterator = win32file.FindFilesIterator(unicode_path + '\\*')

        FILE_ATTRIBUTE = 0
        FILE_NAME = 8
        FILE_ATTRIBUTE_DIRECTORY_VISTA = 8208
        for file_info in folder_iterator:
            if file_info[FILE_NAME] == '.' or file_info[FILE_NAME] == '..':
                continue
            if (file_info[FILE_ATTRIBUTE] == win32file.FILE_ATTRIBUTE_DIRECTORY
                    or file_info[FILE_ATTRIBUTE]
                    == FILE_ATTRIBUTE_DIRECTORY_VISTA):
                self._deleteFolderWin32('%s\\%s' %
                                        (full_path, file_info[FILE_NAME]))
                continue
            else:
                win32file.DeleteFileW('%s\\%s' %
                                      (unicode_path, file_info[FILE_NAME]))
        del folder_iterator
        win32file.RemoveDirectory(unicode_path)
Ejemplo n.º 5
0
    def _acquire_backup_files(self, shadows):

        for shadow in shadows:

            (linkdir, unused) = self._get_vss_dir(shadow)

            self.aq.refreshgui()
            self._get_vss_reg_files(linkdir, 0)
            self.aq.refreshgui()

            win32file.RemoveDirectory(linkdir)
Ejemplo n.º 6
0
 def test_format_pywintypes_error(self):
     self.requireFeature(features.pywintypes)
     import pywintypes
     import win32file
     try:
         win32file.RemoveDirectory('nosuchfile22222')
     except pywintypes.error:
         msg = _format_exception()
     # GZ 2010-05-03: Formatting for pywintypes.error is basic, a 3-tuple
     #                with errno, function name, and locale error message
     self.assertContainsRe(
         msg, "^brz: ERROR: \\(2, 'RemoveDirectory[AW]?', .*\\)")
Ejemplo n.º 7
0
def Execute(op):
    """実行処理。リトライが必要になった項目数を返す。"""
    retry = 0
    try:
        f = op.instructions["target"]
    except KeyError:
        log.error("Required key is not specified.")
        return False
    # end 処理刷るものなし
    op.output["all_OK"] = True
    op.output["retry"]["target"] = []
    lst = []
    for elem in f:
        if os.path.isfile(elem):
            lst.append(elem)
        else:
            for elem2 in misc.IteratePaths(elem):
                lst.append(elem2)
            # end フォルダからファイルリスト
            lst.append(elem)  # イテレーションの最後に親フォルダ追加
        # end フォルダだった
    # end ファイルリスト作るループ
    # ファイルリスト作ったので、もともとの target に上書き
    f = lst
    for elem in f:
        try:
            if os.path.isfile(elem):
                win32file.DeleteFile(elem)
            else:
                win32file.RemoveDirectory(elem)
        except win32file.error as err:
            if helper.CommonFailure(op, elem, err, log):
                appendRetry(op.output, elem)
            continue
        # end except
        op.output["succeeded"] += 1
    # end 削除処理
    if len(op.output["retry"]["target"]) > 0:
        op.output["retry"]["operation"] = VERB
        retry = len(op.output["retry"]["target"])
    # end リトライあるか
    return retry
Ejemplo n.º 8
0
    def process3(self):

        answer3 = 5

        while answer3 != '10':
            print('1 - To create directory\n'
                  '2 - To remove directory\n'
                  '10 - To exit to menu')

            answer3 = input()

            if answer3 == '1':
                print("Enter the name of directory\n")
                directory = input()
                win32file.CreateDirectory(directory, None)

            elif answer3 == '2':
                print("Enter the name of directory to delete\n")
                directory = input()
                win32file.RemoveDirectory(directory, None)
        answer = 9
Ejemplo n.º 9
0
        try:
            # GetFileAttributes automatically calls GetFileAttributesW when
            # passed unicode
            try:
                attr = win32api.GetFileAttributes(fname)
            except win32api.error, details:
                if details[0] != winerror.ERROR_FILENAME_EXCED_RANGE:
                    raise

            attr = win32api.GetFileAttributes(unicode(fname))
            self.failUnless(attr & win32con.FILE_ATTRIBUTE_DIRECTORY, attr)

            long_name = win32api.GetLongPathNameW(fname)
            self.failUnlessEqual(long_name, fname)
        finally:
            win32file.RemoveDirectory(fname)


class FormatMessage(unittest.TestCase):
    def test_FromString(self):
        msg = "Hello %1, how are you %2?"
        inserts = ["Mark", "today"]
        result = win32api.FormatMessage(
            win32con.FORMAT_MESSAGE_FROM_STRING,
            msg,  # source
            0,  # ID
            0,  # LangID
            inserts)
        self.assertEqual(result, "Hello Mark, how are you today?")

Ejemplo n.º 10
0
def remove_directory(path):
    # Windows API call
    win32file.RemoveDirectory(path)
Ejemplo n.º 11
0
def Execute(op, resume=False):
    """実行処理。リトライが必要になった項目数を返す。"""
    if resume:
        log.debug("Starting as resume mode...")
    retry = 0
    try:
        f = op.instructions["target"]
    except KeyError:
        log.error("Required key is not specified.")
        return False
    # end 処理刷るものなし
    copy_move_flag = op.instructions["copy_move_flag"]
    if not resume:  # resume modeではない=初期化
        op.output["all_OK"] = True
        op.output["retry"]["target"] = []
        op.output["percentage"] = 0
        op.output["copy_move_flag"] = copy_move_flag
    # end 初期化
    log.debug("Retrieving file list...")
    lst = []
    for elemt in f:
        elem = elemt[0]
        dest = elemt[1]
        basepath = os.path.dirname(elem)
        if os.path.isfile(elem):
            lst.append(Element(elem, basepath, dest))
        else:
            e = Element(elem, basepath, dest)
            if os.path.isdir(e.destpath) and not resume:
                # フォルダがもうあれば、その時点で確認に入れる(中のフォルダを展開しない)
                # コピー先にディレクトリがあった時点で、「ディレクトリを上書きしますか?」の確認を出したいので。
                _processExistingFolder(op.output, elem, basepath, destpath)
            else:  # まだないか、ユーザーに確認済みなので追加
                _expandFolder(lst, elem, e, basepath, dest, copy_move_flag)
            # end フォルダを展開するかしないか
        # end フォルダだった
    # end ファイルリスト作るループ
    # ファイルリスト作ったので、もともとの target に上書き
    f = lst
    log.debug("%d items found." % len(f))
    # コピーサイズの合計を計算
    total = 0
    for elem in f:
        if elem.size != -1:
            total += elem.size
    # end サイズを足す
    op.output['total_bytes'] = total
    op.output['current_bytes'] = 0
    log.debug("Size: %d bbytes" % total)
    log.debug("Start copying...")
    overwrite = resume
    pasted_size = 0
    for elem in f:
        if elem.destpath is None:  # フォルダ削除用
            # 移動するとき、 destpath が空のエントリーは、フォルダを消すという命令代わりに使っている。
            log.debug("deleting folder %s" % elem.path)
            try:
                win32file.RemoveDirectory(elem.path, None)
            except win32file.error as err:
                log.debug(
                    "Error encountered when trying to delete moved folder: %s"
                    % str(err))
            # end except
            continue  # エラーにならないように逃げる
        # end フォルダ消す
        try:
            if elem.isfile:
                copyOrMove(elem, copy_move_flag, overwrite)
            else:
                if resume and os.path.isdir(elem.destpath):
                    continue  # 再開している場合はエラーになる前に逃げる
                win32file.CreateDirectory(elem.destpath, None)
        except win32file.error as err:
            log.error("Cannot create %s (%s)" % (elem.destpath, str(err)))
            ProcessError(op, elem, str(err), resume)
            continue
        # end except
        op.output["succeeded"] += 1
        if elem.size != -1:
            pasted_size += elem.size
        if total == 0:
            percentage = 100
        else:
            percentage = int(pasted_size / total * 100)
        op.SetPercentage(percentage)
    # end 削除処理
    if len(op.output["retry"]["target"]) > 0:
        op.output["retry"]["operation"] = VERB
        retry = len(op.output["retry"]["target"])
    # end リトライあるか
    # 終わった者はもう使わないので、ファイルリストは消してしまう
    op.instructions["target"] = []
    return retry