示例#1
0
def testSHFileOperation(file_cnt):
    temp_dir = os.environ["temp"]
    orig_fnames = [
        win32api.GetTempFileName(temp_dir, "sfo")[0] for x in range(file_cnt)
    ]
    new_fnames = [
        os.path.join(temp_dir, "copy of " + os.path.split(orig_fnames[x])[1])
        for x in range(file_cnt)
    ]

    pFrom = "\0".join(orig_fnames)
    pTo = "\0".join(new_fnames)

    shell.SHFileOperation((
        0,
        shellcon.FO_MOVE,
        pFrom,
        pTo,
        shellcon.FOF_MULTIDESTFILES | shellcon.FOF_NOCONFIRMATION,
    ))
    for fname in orig_fnames:
        assert not os.path.isfile(fname)

    for fname in new_fnames:
        assert os.path.isfile(fname)
        shell.SHFileOperation((
            0,
            shellcon.FO_DELETE,
            fname,
            None,
            shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NOERRORUI,
        ))
示例#2
0
def test_usb(type, fmt=False):
    if fmt:
        os.system('adb reboot')
        os.system('adb wait-for-device')
        while os.popen('adb shell getprop sys.boot_completed').readline(
        ).strip() != '1':
            time.sleep(3)
    os.popen('adb push \"{0}\" /data/local/tmp'.format(
        os.path.join(workdir, 'ramdisk.sh'))).readlines()
    os.popen('adb shell sh /data/local/tmp/ramdisk.sh').readlines()
    os.system('adb shell setprop sys.usb.config {0},adb'.format(type))
    os.system('adb wait-for-device')
    drive = None
    loop = 1
    read = 0
    write = 0
    while not drive:
        if loop > 20:
            break
        r = win32file.GetLogicalDrives()
        for d in range(26):
            if r >> d & 1 and win32file.GetDriveType(string.ascii_letters[d] +
                                                     ':\\') == 2:
                drive = string.ascii_letters[d]
                break
        time.sleep(3)
        loop += 1
    if drive:
        if fmt:
            os.system('echo y | format {0}: /fs:fat32 /q'.format(drive))

        file1 = os.path.join(workdir, 'test.zip')
        file2 = os.path.join(drive + ':' + os.sep, 'test.zip')
        if os.path.exists(file2):
            os.remove(file2)

        st = time.time()
        shell.SHFileOperation(
            (0, shellcon.FO_COPY, file1, file2, 0, None, None))
        write = round(
            os.path.getsize(file1) / 1048576.0 / (time.time() - st), 2)

        file3 = os.path.join(workdir, 'tmp.zip')
        if os.path.exists(file3):
            os.remove(file3)

        st = time.time()
        shell.SHFileOperation(
            (0, shellcon.FO_COPY, file2, file3, 0, None, None))
        read = round(
            os.path.getsize(file2) / 1048576.0 / (time.time() - st), 2)

        os.remove(file2)
        os.remove(file3)
    os.popen('adb shell rm /data/local/tmp/ramdisk.sh').readlines()
    return (read, write)
示例#3
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"] = []
    for elem in f:
        sh = (0, shellcon.FO_DELETE, elem, None, shellcon.FOF_ALLOWUNDO
              | shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NO_UI, None, "")
        ret = shell.SHFileOperation(sh)
        if ret[0] != 0:
            if helper.CommonFailure(op, elem, ret[0], 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
示例#4
0
def check_manual(deskdir, file_type):
    answer = 'n'
    tmp_num = 0
    deleted_num = 0
    while True:
        answer = input("你确定要删除上面这些目录或文件吗? Y or N?\r\n").lower()
        if answer in ('y', 'n'):
            break
    if answer == 'y':
        for filename in traversal_dir(deskdir, file_type):
            logger.debug(filename)
            tmp_num += 1
            if os.path.exists(filename) and os.path.isfile(filename):
                # os.remove(str(filename))
                # 删除到回收站
                result, aborted = shell.SHFileOperation(
                    (0, shellcon.FO_DELETE, str(filename), None,
                     shellcon.FOF_SILENT | shellcon.FOF_ALLOWUNDO
                     | shellcon.FOF_NOCONFIRMATION, None, None))  #删除文件到回收站
                if not aborted and result != 0:
                    logger.error(
                        "Error, file: {} can't be deleted!!".format(filename))
                    raise WindowsError('SHFileOperation failed: 0x%08x' %
                                       result)

                else:
                    deleted_num += 1

    logger.debug("已经清理桌面上的{}文件[{}]个.".format(file_type, deleted_num))
示例#5
0
 def testRename(self):
     s = (0, FO_RENAME, self.src_name, self.dest_name)  # hwnd,  # operation
     rc, aborted = shell.SHFileOperation(s)
     self.assertTrue(not aborted)
     self.assertEqual(0, rc)
     self.assertTrue(os.path.isfile(self.dest_name))
     self.assertTrue(not os.path.isfile(self.src_name))
示例#6
0
 def delete(self, ref):
     path = self._abspath(ref)
     # FOF_ALLOWUNDO send to Trash
     res = shell.SHFileOperation((0, shellcon.FO_DELETE, path, None,
                                  shellcon.FOF_NOCONFIRMATION|shellcon.FOF_ALLOWUNDO, None, None))
     if res[0] != 0:
         raise IOError(res)
示例#7
0
def testSHNAMEMAPPINGS(file_cnt):
    ## attemps to move a set of files to names that already exist, and generated filenames should be returned
    ##   as a sequence of 2-tuples created from SHNAMEMAPPINGS handle
    temp_dir = os.environ["temp"]
    orig_fnames = [
        win32api.GetTempFileName(temp_dir, "sfo")[0] for x in range(file_cnt)
    ]
    new_fnames = [
        win32api.GetTempFileName(temp_dir, "sfo")[0] for x in range(file_cnt)
    ]
    pFrom = "\0".join(orig_fnames)
    pTo = "\0".join(new_fnames)
    rc, banyaborted, NameMappings = shell.SHFileOperation((
        0,
        shellcon.FO_MOVE,
        pFrom,
        pTo,
        shellcon.FOF_MULTIDESTFILES
        | shellcon.FOF_NOCONFIRMATION
        | shellcon.FOF_RENAMEONCOLLISION
        | shellcon.FOF_WANTMAPPINGHANDLE,
    ))

    for old_fname, new_fname in NameMappings:
        print("Old:", old_fname, "New:", new_fname)
    assert len(NameMappings) == file_cnt
示例#8
0
 def _ensure_remove(function, path, exc_info):
     '''onerror callback for rmtree that tries hard to delete files'''
     if issubclass(exc_info[0], WindowsError):
         import winerror
         # Delete read-only files
         # https://bugs.python.org/issue19643
         # https://bugs.python.org/msg218021
         if exc_info[1].winerror == winerror.ERROR_ACCESS_DENIED:
             os.chmod(path, stat.S_IWRITE)
             return os.remove(path)
         # Delay delete a bit if directory is used by another process.
         # Typically happens on uninstall immediately after bower / npm / git
         # (e.g. during testing.)
         elif exc_info[1].winerror == winerror.ERROR_SHARING_VIOLATION:
             delays = [
                 0.001, 0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1.0
             ]
             for delay in delays:
                 time.sleep(delay)
                 try:
                     return os.remove(path)
                 except WindowsError:
                     pass
         # npm creates windows shortcuts that shutil.rmtree cannot delete.
         # os.listdir failes with a PATH_NOT_FOUND. Delete these and try again
         elif function == os.listdir and exc_info[
                 1].winerror == winerror.ERROR_PATH_NOT_FOUND:
             app_log.error('Cannot delete %s', path)
             from win32com.shell import shell, shellcon
             options = shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NOERRORUI
             code, err = shell.SHFileOperation(
                 (0, shellcon.FO_DELETE, path, None, options))
             if code == 0:
                 raise TryAgainError()
     raise exc_info[1]
示例#9
0
 def testMove(self):
     s = (0, FO_MOVE, self.src_name, self.dest_name)  # hwnd,  # operation
     rc, aborted = shell.SHFileOperation(s)
     self.failUnless(not aborted)
     self.failUnlessEqual(0, rc)
     self.failUnless(os.path.isfile(self.dest_name))
     self.failUnless(not os.path.isfile(self.src_name))
示例#10
0
def trash(path , dlg=False):
    path = os.path.abspath(path)
    path = unicode(path)
    #区切り文字はバックスラッシュ
    path = path.replace("/", "\\")
    
    #\で終わっていると削除できない
    for i,c in enumerate(reversed(path)):
        if c != u"\\":
            if i==0:
                pass
            else:
                path = path[0:-i]
            break
    if not dlg:
        Flags = FOF_NOCONFIRMATION | FOF_ALLOWUNDO | FOF_SILENT
    else:
        Flags = FOF_NOCONFIRMATION | FOF_ALLOWUNDO# フラグ
    
    s = (
        0, # hwnd,
        FO_DELETE, #operation
        path,
        u"",
        Flags
    )
    shell.SHFileOperation(s)
示例#11
0
 def recycle_path(path):
     from win32com.shell import shell, shellcon
     flags = (shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NOCONFIRMMKDIR | shellcon.FOF_NOERRORUI |
              shellcon.FOF_SILENT | shellcon.FOF_RENAMEONCOLLISION)
     retcode, aborted = shell.SHFileOperation((0, shellcon.FO_DELETE, path, None, flags, None, None))
     if retcode != 0 or aborted:
         raise RuntimeError('Failed to delete: %r with error code: %d' % (path, retcode))
示例#12
0
def delDir(dirname):
    if SUPPORT_SHELL:
        shell.SHFileOperation(
            (0, shellcon.FO_DELETE, dirname, None, shellcon.FOF_SILENT
             | shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION, None,
             None))  #删除文件到回收站
    else:
        shutil.rmtree(dirname)
示例#13
0
 def move(self, ref, new_parent_ref, name=None):
     path = self._abspath(ref)
     if name is None:
         name = os.path.basename(path)
     new_path = os.path.join(self._abspath(new_parent_ref), name)
     res = shell.SHFileOperation((0, shellcon.FO_MOVE, path, new_path, shellcon.FOF_NOCONFIRMATION, None, None))
     if res[0] != 0:
         raise IOError(res)
示例#14
0
 def copy(self, srcref: RawPath, dstref: RawPath) -> None:
     """Make a copy of the file (with xattr included)."""
     src = str(self.abspath(srcref))
     dst = str(self.abspath(dstref))
     res = shell.SHFileOperation((0, shellcon.FO_COPY, src, dst,
                                  shellcon.FOF_NOCONFIRMATION, None, None))
     if res[0] != 0:
         raise OSError(res, locals())
示例#15
0
 def testDelete(self):
     s = (0,  # hwnd,
          FO_DELETE,  # operation
          self.src_name, None,
          FOF_NOCONFIRMATION)
     rc, aborted = shell.SHFileOperation(s)
     assert not aborted
     assert 0 == rc
     assert not os.path.isfile(self.src_name)
示例#16
0
 def rename(self, srcref, to_name):
     parent = os.path.dirname(srcref)
     path = self.abspath(srcref)
     new_path = os.path.join(os.path.dirname(path), to_name)
     res = shell.SHFileOperation((0, shellcon.FO_RENAME, path, new_path,
                                  shellcon.FOF_NOCONFIRMATION, None, None))
     if res[0] != 0:
         raise IOError(res, locals())
     return MockFile(os.path.join(parent, to_name))
示例#17
0
 def testDelete(self):
     s = (0, # hwnd,
          FO_DELETE, #operation
          self.src_name, None,
          FOF_NOCONFIRMATION)
     rc, aborted = shell.SHFileOperation(s)
     self.failUnless(not aborted)
     self.failUnlessEqual(0, rc)
     self.failUnless(not os.path.isfile(self.src_name))
示例#18
0
 def deltorecyclebin(self, filename):
     # print('deltorecyclebin', filename)
     # os.remove(filename) #直接删除文件,不经过回收站
     res = shell.SHFileOperation(
         (0, shellcon.FO_DELETE, filename, None,
          shellcon.FOF_SILENT | shellcon.FOF_ALLOWUNDO
          | shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NOERRORUI, None,
          None))  # 删除文件到回收站
     if not res[1]:
         os.system('del ' + filename)
示例#19
0
 def testMove(self):
     s = (0,  # hwnd,
          FO_MOVE,  # operation
          self.src_name,
          self.dest_name)
     rc, aborted = shell.SHFileOperation(s)
     assert not aborted
     assert 0 == rc
     assert os.path.isfile(self.dest_name)
     assert not os.path.isfile(self.src_name)
示例#20
0
 def testRename(self):
     s = (0, # hwnd,
          FO_RENAME, #operation
          self.src_name,
          self.dest_name)
     rc, aborted = shell.SHFileOperation(s)
     self.failUnless(not aborted)
     self.failUnlessEqual(0, rc)
     self.failUnless(os.path.isfile(self.dest_name))
     self.failUnless(not os.path.isfile(self.src_name))
示例#21
0
def CopyFolder(source, target):
    cprint("Copying Folder Source %s to: %s " % (source, target), "yellow")
    try:
        shell.SHFileOperation(
            (0, shellcon.FO_COPY, source, target, shellcon.FOF_SILENT
             | shellcon.FOF_RENAMEONCOLLISION | shellcon.FOF_NO_UI
             | shellcon.FOF_NOCONFIRMMKDIR | shellcon.FOF_NOCOPYSECURITYATTRIBS
             | shellcon.FOF_NOCONFIRMATION, None, None))
    except Exception as er:
        print("Move Folder Exception: %s" % type(er).__name__)
示例#22
0
def del_selected():
    seleced = tree.selection()
    for item in seleced:
        filename = tree.item(item, "values")[0]
        print(filename)
        shell.SHFileOperation(
            (0, shellcon.FO_DELETE, filename, None, shellcon.FOF_SILENT
             | shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION, None,
             None))  #删除文件到回收站
        tree.delete(item)
    tkinter.messagebox.showinfo('提示', '已删除选中的webshell')
示例#23
0
def del_all():
    x = tree.get_children()  #返回的是下标元组
    print("children", x)
    for item in x:
        filename = tree.item(item, "values")[0]
        shell.SHFileOperation(
            (0, shellcon.FO_DELETE, filename, None, shellcon.FOF_SILENT
             | shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION, None,
             None))  #删除文件到回收站
        tree.delete(item)
    tkinter.messagebox.showinfo('提示', '已删除全部webshell')
示例#24
0
 def testMove(self):
     s = (
         0,  # hwnd,
         FO_MOVE,  # operation
         self.src_name,
         self.dest_name)
     rc, aborted = shell.SHFileOperation(s)
     self.assertTrue(not aborted)
     self.assertEqual(0, rc)
     self.assertTrue(os.path.isfile(self.dest_name))
     self.assertTrue(not os.path.isfile(self.src_name))
示例#25
0
 def recycle(self, filename):
     try:
         if not os.path.exists(filename):
             return True
         res = shell.SHFileOperation(
             (0, shellcon.FO_DELETE, filename, None, shellcon.FOF_SILENT
              | shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION, None,
              None))
         if not res[1]:
             os.remove(filename)
     except Exception as e:
         pass
示例#26
0
def _file_operation(
    operation,
    source_path,
    target_path=None,
    allow_undo=True,
    no_confirm=False,
    rename_on_collision=True,
    silent=False,
    extra_flags=0,
    hWnd=None
):
    flags = extra_flags
    #
    # At present the Python wrapper around SHFileOperation doesn't
    # allow lists of files. Hopefully it will at some point, so
    # take account of it here.
    # If you pass this shell function a "/"-separated path with
    # a wildcard, eg c:/temp/*.tmp, it gets confused. It's ok
    # with a backslash, so convert here.
    #
    source_path = source_path or ""
    if isinstance(source_path, str):
        source_path = os.path.abspath(source_path)
    else:
        source_path = "\0".join(os.path.abspath(i) for i in source_path)

    target_path = target_path or ""
    if isinstance(target_path, str):
        target_path = os.path.abspath(target_path)
    else:
        target_path = "\0".join(os.path.abspath(i) for i in target_path)
        flags |= shellcon.FOF_MULTIDESTFILES

    flags |= shellcon.FOF_WANTMAPPINGHANDLE
    if allow_undo:
        flags |= shellcon.FOF_ALLOWUNDO
    if no_confirm:
        flags |= shellcon.FOF_NOCONFIRMATION
    if rename_on_collision:
        flags |= shellcon.FOF_RENAMEONCOLLISION
    if silent:
        flags |= shellcon.FOF_SILENT
    flags |= extra_flags

    result, n_aborted, mapping = shell.SHFileOperation(
       (hWnd or 0, operation, source_path, target_path, flags, None, None)
    )
    if result != 0:
        raise x_winshell(result)
    elif n_aborted:
        raise x_winshell("%d operations were aborted by the user" % n_aborted)

    return dict(mapping)
示例#27
0
文件: app.py 项目: Kahsolt/pic-dedup
 def pic_delete_(self, pic, what='item'):
   fp = pic.path
   
   if what == 'file':
     if os.path.exists(fp):
       res = shell.SHFileOperation((0, shellcon.FO_DELETE, fp, None,
                                    shellcon.FOF_SILENT | shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION,
                                    None, None))
       if res[0] == 0: logging.info('[RecycleBin] file %r deleted' % fp)
       self.var_stat_msg.set("Delete %r done." % fp)
   
   self.tv.delete(self.tv.selection()[0])
示例#28
0
def deltoreCyclebin(filename):
    #直接删除文件,不经过回收站
    #os.remove(filename)
    if not debug:
        #删除文件到回收站
        res = shell.SHFileOperation(
            (0, shellcon.FO_DELETE, filename, None, shellcon.FOF_SILENT
             | shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION, None,
             None))
        print(res)
        if not res[1]:
            os.system('del ' + filename)
示例#29
0
def file_recycle(fullpath, silent: bool = True) -> bool:
    ''' Move file to the recycle bin
		silent - do not show standard windows
		dialog to confirm deletion.
		Returns True on successful operation.
	'''
    fullpath = _fix_fullpath(fullpath)
    flags = shellcon.FOF_ALLOWUNDO
    if silent:
        flags = flags | shellcon.FOF_SILENT | shellcon.FOF_NOCONFIRMATION
    result = shell.SHFileOperation(
        (0, shellcon.FO_DELETE, fullpath, None, flags, None, None))
    return result[0] <= 3
示例#30
0
 def delete(self, ref: RawPath) -> None:
     path = self.abspath(ref)
     # FOF_ALLOWUNDO send to Trash
     res = shell.SHFileOperation((
         0,
         shellcon.FO_DELETE,
         str(path),
         None,
         shellcon.FOF_NOCONFIRMATION | shellcon.FOF_ALLOWUNDO,
         None,
         None,
     ))
     if res[0] != 0:
         raise OSError(res, locals())