示例#1
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)
示例#2
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))
示例#3
0
    def win32Spawn(sh, escape, cmd, args, spawnEnv):
        for var in spawnEnv:
            spawnEnv[var] = spawnEnv[var].encode("ascii", "replace")

        #sAttrs = win32security.SECURITY_ATTRIBUTES()
        #sAttrs.bInheritHandle = 1
        #hStdinR, hStdinW = win32pipe.CreatePipe(sAttrs, 0)
        #hStdoutR, hStdoutW = win32pipe.CreatePipe(sAttrs, 0)
        #hStderrR, hStderrW = win32pipe.CreatePipe(sAttrs, 0)
        #
        #pid = win32api.GetCurrentProcess()
        #
        #def replaceHandle(handle) :
        #  tmp = win32api.DuplicateHandle(pid, handle, pid, 0, 0, win32con.DUPLICATE_SAME_ACCESS)
        #  win32file.CloseHandle(handle)
        #  return tmp
        #
        #hStdinW = replaceHandle(hStdinW)
        #hStdoutR = replaceHandle(hStdoutR)
        #hStderrR = replaceHandle(hStderrR)

        sAttrs = win32security.SECURITY_ATTRIBUTES()
        startupInfo = win32process.STARTUPINFO()
        #startupInfo.hStdInput = hStdinR
        #startupInfo.hStdOutput = hStdoutW
        #startupInfo.hStdError = hStderrW
        #startupInfo.dwFlags = win32process.STARTF_USESTDHANDLES
        newArgs = " ".join(map(escape, args[1:]))
        cmdLine = cmd + " " + newArgs

        # check for any special operating system commands
        if cmd == "del":
            for arg in args[1:]:
                win32file.DeleteFile(arg)
            exitCode = 0
        else:
            # otherwise execute the command.
            try:
                hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(
                    None, cmdLine, None, None, 1, 0, spawnEnv, None,
                    startupInfo)
            except:
                errorCode = win32api.GetLastError()
                raise RuntimeError("Could not execute the following " +
                                   "command line (error code {}): {}".format(
                                       errorCode, cmdLine))
            win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
            exitCode = win32process.GetExitCodeProcess(hProcess)

            #win32file.CloseHandle(hStdinR)
            #win32file.CloseHandle(hStdoutW)
            #win32file.CloseHandle(hStderrW)
            #with os.fdopen(msvcrt.open_osfhandle(hStdoutR, 0), "rb") as f: stdout = f.read()
            #with os.fdopen(msvcrt.open_osfhandle(hStderrR, 0), "rb") as f: stderr = f.read()
            #sys.stdout.write(stdout)
            #sys.stderr.write(stderr)

            win32file.CloseHandle(hProcess)
            win32file.CloseHandle(hThread)
        return exitCode
示例#4
0
def haveWritePerm(directory):
    """ Test a directory for write permissions """
    rand = genPasswd(len=32)
    pathname = directory + "\\" + rand
    if not os.path.exists(pathname):
        try:
            f = open(pathname, "w")
        except EnvironmentError:
            return 0
        f.close()
        win32file.DeleteFile(pathname)
        return 1
示例#5
0
def os_link(src, dst):
    try:
        win32file.CreateHardLink(dst, src)
        # CreateHardLink sometimes succeeds on mapped drives but
        # following nlinks() returns 1. Check it now and bail out.
        if nlinks(src) < 2:
            try:
                win32file.DeleteFile(dst)
            except:
                pass
            # Fake hardlinking error
            raise OSError(errno.EINVAL, 'Hardlinking not supported')
    except pywintypes.error, details:
        raise OSError(errno.EINVAL, 'target implements hardlinks improperly')
示例#6
0
def os_link(src, dst):
    try:
        win32file.CreateHardLink(dst, src)
        # CreateHardLink sometimes succeeds on mapped drives but
        # following nlinks() returns 1. Check it now and bail out.
        if nlinks(src) < 2:
            try:
                win32file.DeleteFile(dst)
            except:
                pass
            # Fake hardlinking error
            raise WinOSError((18, 'CreateHardLink', 'The system cannot '
                              'move the file to a different disk drive'))
    except pywintypes.error, details:
        raise WinOSError(details)
示例#7
0
 def writeProxy(self):
     tmpFile = file("ptmp.txt", "w+")
     numP = len(self.proxySet)
     randomInt = getRandomIntSet( numP )
     for idx in randomInt:
         if idx>=0 and idx<numP:
             proxy = self.proxySet[idx]
             line = proxy[0] + " " + str(proxy[1]) + "\r\n"
             tmpFile.write(line)
         else:
             logging.error("proxy random error: " + str(idx))
     tmpFile.close()
     uFile = self.proxyFile
     win32file.DeleteFile(uFile)
     win32file.CopyFile(u"ptmp.txt", uFile, False)
示例#8
0
def RemoveWriteDAC(fname):
    try:
        win32file.DeleteFile(fname)
    except:
        pass

    my_dacl = "D:(D;;WD;;;SY)(A;;GA;;;WD)"
    se_obj = MakeDaclStringToSeObj(my_dacl)
    fdacl = se_obj.GetSecurityDescriptorDacl()
    in_se_attr = win32security.SECURITY_ATTRIBUTES()
    in_se_attr.SECURITY_DESCRIPTOR = se_obj
    ret = win32security.SetNamedSecurityInfo(fname, SE_FILE_OBJECT, 
        OWNER_SECURITY_INFORMATION|GROUP_SECURITY_INFORMATION|DACL_SECURITY_INFORMATION|PROTECTED_DACL_SECURITY_INFORMATION,
        my_sid, my_sid, fdacl, None)
    if ret == None:
        print '[*] Removed WriteDAC for System.'
    else:
        print '[!] Error while removing WriteDAC for System.'
示例#9
0
 def writeUrlConfig(self):
     try:
         wb = xlwt.Workbook()
         sheet = wb.add_sheet('sheet 1')
         for row_index in range(len(self.baobeiSet)):
             baobei = self.baobeiSet[row_index]
             num = baobei[0]-1
             url = baobei[1]
             sheet.write(row_index,0,num)
             sheet.write(row_index,1,url)
         sheet.col(1).width = 3333*8
         filePath = "UrlConfig_backup.xls"
         wb.save(filePath)
         win32file.DeleteFile(u"UrlConfig.xls")
         win32file.CopyFile(u"UrlConfig_backup.xls", u"UrlConfig.xls", False)
     except:
         logging.error("UrlConfig_backup.xls write error!")
         traceStr = traceback.format_exc()
         logging.error(traceStr)
示例#10
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
示例#11
0
 def my_spawn(sh, escape, cmd, args, spawnenv):
     for var in spawnenv:
         spawnenv[var] = spawnenv[var].encode('ascii', 'replace')
     sAttrs = win32security.SECURITY_ATTRIBUTES()
     StartupInfo = win32process.STARTUPINFO()
     newargs = ' '.join(map(escape, args[1:]))
     cmdline = cmd + " " + newargs
     # check for any special operating system commands
     if cmd == 'del':
         for arg in args[1:]:
             win32file.DeleteFile(arg)
         exit_code = 0
     else:
         # otherwise execute the command.
         hProcess, hThread, dwPid, dwTid = win32process.CreateProcess(None, cmdline, None, None, 1, 0, spawnenv, None, StartupInfo)
         win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
         exit_code = win32process.GetExitCodeProcess(hProcess)
         win32file.CloseHandle(hProcess);
         win32file.CloseHandle(hThread);
     return exit_code
示例#12
0
 def delete_originals(self):
     import win32file
     for path in self.handle_map.iterkeys():
         win32file.DeleteFile(path)
     self.close_handles()
示例#13
0
def delete_file(path):
    # Windows API call
    win32file.DeleteFile(path)
示例#14
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
        #ベースパスを決定
        op.output["basepath"] = os.path.dirname(f[0])
        op.output["destpath"] = op.instructions['to']
    #end 初期化
    basepath = op.output["basepath"]
    destpath = op.output["destpath"]
    log.debug("Base path: %s dest path: %s" % (basepath, destpath))
    log.debug("Retrieving file list...")
    lst = []
    for elem in f:
        if not basepath in elem:
            debug.log("Ummatched base path, skipping %s" % elem)
            continue
        #end ベースパスが合わない
        if os.path.isfile(elem):
            lst.append(Element(elem, basepath, destpath))
        else:
            e = Element(elem, basepath, destpath)
            if os.path.isdir(e.destpath) and not resume:
                _processExistingFolder(
                    op.output, elem)  #フォルダがもうあれば、その時点で確認に入れる(中のフォルダを展開しない)
            else:  #まだないか、確認済みなので追加
                _expandFolder(lst, elem, e, basepath, destpath)
            #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 = 0 if resume else win32file.COPY_FILE_FAIL_IF_EXISTS
    for elem in f:
        if elem.destpath is None:  #フォルダ削除用
            try:
                win32.RemoveDirectory(elem.path, None)
            except win32file.error as err:
                log.debug(
                    "Error encountered when trying to delete moved folder: %s"
                    % str(err))
            #end except
        #end フォルダ消す
        try:
            if elem.isfile:
                win32file.CopyFileEx(elem.path, elem.destpath, None, None,
                                     False, 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.output, elem, str(err), resume)
            continue
        #end except
        if copy_move_flag == MOVE:
            try:
                if elem.isfile: win32file.DeleteFile(elem.path)
            except win32file.error as err:
                log.debug("Error encountered when deleting moved file: %s" %
                          str(err))
            #end except
        #end 移動モード
        op.output["succeeded"] += 1
    #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