Exemplo n.º 1
0
def mkdir(file_path: str, mode: int = 0o777) -> None:
    """
    Rewrite of original os.mkdir function, that will ensure on Windows that given mode
    is correctly applied.

    :param str file_path: The file path to open
    :param int mode: POSIX mode to apply on directory when created, Python defaults
                     will be applied if ``None``
    """
    if POSIX_MODE:
        return os.mkdir(file_path, mode)

    attributes = win32security.SECURITY_ATTRIBUTES()
    security = attributes.SECURITY_DESCRIPTOR
    user = _get_current_user()
    dacl = _generate_dacl(user, mode, _WINDOWS_UMASK.mask)
    security.SetSecurityDescriptorOwner(user, False)
    security.SetSecurityDescriptorDacl(1, dacl, 0)

    try:
        win32file.CreateDirectory(file_path, attributes)
    except pywintypes.error as err:
        # Handle native windows error into python error to be consistent with the API
        # of os.mkdir in the situation of a directory already existing.
        if err.winerror == winerror.ERROR_ALREADY_EXISTS:
            raise OSError(errno.EEXIST, err.strerror, file_path, err.winerror)
        raise err

    return None
Exemplo n.º 2
0
def quiet_mkdir(path):
    # dropping to win32 for Windows
    # python modifies the permissions on Windows folders being created to be too permissive so we manually specify security info
    if sys.platform == "win32":
        import pywintypes
        import win32file
        import win32security
        try:
            """
            Owner            :
            Group            :
            DiscretionaryAcl : {NT AUTHORITY\SYSTEM: AccessAllowed (GenericAll), BUILTIN\Administrators: AccessAllowed (GenericAll)}
            SystemAcl        : {}
            RawDescriptor    : System.Security.AccessControl.CommonSecurityDescriptor
            """
            sddl = "D:PAI(A;OICI;GA;;;SY)(A;OICI;GA;;;BA)"
            sec_descriptor = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
                sddl, win32security.SDDL_REVISION_1)
            sec_attributes = win32security.SECURITY_ATTRIBUTES()
            sec_attributes.SECURITY_DESCRIPTOR = sec_descriptor
            win32file.CreateDirectory(path, sec_attributes)
        except pywintypes.error:
            if not os.path.isdir(path):
                raise
    else:
        try:
            os.mkdir(path)
        except OSError:
            if not os.path.isdir(path):
                raise
def protocol(plist,drive,clientid,idict,expiry,numsess,dongle,disallow):
    "writes files, such to SD"
    for protocol,layout in plist:
        dpath=drive+'\\'+clientid+'\\'+protocol
        try:
            win32file.CreateDirectory(dpath,None)
        except:
            pass    # ignore error if already exists
        # copy *.ini to SD
        fls=glob.glob(idict['EDICT']['DATAPATH']+'\\'+clientid+'\\'+protocol+'\\*.ini')
        for f in fls:
            shutil.copy2(f,dpath+'\\')
        fls=glob.glob(idict['EDICT']['DATAPATH']+'\\'+clientid+'\\'+protocol+'\\stages.*')
        for f in fls:
            shutil.copy2(f,dpath+'\\')
        
        idict['expiry']=expiry
        idict['numsess']=numsess
        idict['rdongle']=dongle
        idict['rid']=clientid
        idict['rproto']=protocol
        idict['rlayout']=layout
        idict['rdisallow']=disallow
        idict['rpath']=dpath+'\\'
        
        try:
            anskind=pyaccess.CreateUserFile(idict)
        except:
            return 999
        if anskind:
            return anskind

    return 0
Exemplo n.º 4
0
def Execute(op):
    """実行処理。リトライが必要になった項目数を返す。"""
    try:
        target = op.instructions["target"]
    except KeyError:
        log.error("target is not specified.")
        return False
    # end 新規フォルダ名がない
    op.output["all_OK"] = True
    op.output["retry"]["target"] = []
    i = 0
    retry = 0
    for elem in target:
        try:
            win32file.CreateDirectory(elem, None)
        except win32file.error as err:
            if helper.CommonFailure(op, elem, err, log):
                appendRetry(op.output, elem)
            continue
        # end except
        op.output["succeeded"] += 1
        i += 1
    # end 項目の数だけ
    if len(op.output["retry"]["target"]) > 0:
        op.output["retry"]["operation"] = VERB
        retry = len(op.output["retry"]["target"])
    # end リトライあるか
    return retry
Exemplo n.º 5
0
def _create_secure_directory_windows(path: str):
    try:
        security_attributes = win32security.SECURITY_ATTRIBUTES()
        security_attributes.SECURITY_DESCRIPTOR = (
            windows_permissions.get_security_descriptor_for_owner_only_perms())
        win32file.CreateDirectory(path, security_attributes)

    except Exception as ex:
        logger.error(f'Could not create a directory at "{path}": {str(ex)}')
        raise ex
Exemplo n.º 6
0
def create_directory(path, sddl):
    # Create security attributes
    security_attributes = win32security.SECURITY_ATTRIBUTES()
    security_attributes.bInheritHandle = 0
    if sddl:
        security_attributes.SECURITY_DESCRIPTOR = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
            sddl, win32security.SDDL_REVISION_1,
        )

    # Windows API call
    win32file.CreateDirectory(path, security_attributes)
def makedrive(drive,clientid,edict):

    cd=IniAid.LoadConfig(edict['DATAPATH']+'\\'+clientid+'\\CLIENT.')
    ans=makedrivesd(drive,clientid,cd['client.fullname'])
    if ans:
        return ans
            

    #   client directory
    win32file.CreateDirectory(drive+'\\'+clientid,None)
    shutil.copy2(edict['DATAPATH']+'\\'+clientid+'\\CLIENT.',drive+'\\'+clientid+'\\CLIENT.')
    # copy client file
    #      client. file
    #      SMR (or whatever) directory
    #           stages.ini  (but not used !!!)
    #      SMRSESS.dat   protected file containing session data and such
    #
    return 0
Exemplo 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
Exemplo n.º 9
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
Exemplo n.º 10
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