Python源码示例:ntpath.normpath()

示例1
def copymode(src, dst, follow_symlinks=True, **kwargs):
    """
    Copy the permission bits from src to dst. The file contents, owner, and group are unaffected. Due to the
    limitations of Windows, this function only sets/unsets the dst's FILE_ATTRIBUTE_READ_ONLY flag based on what src's
    attribute is set to.

    If follow_symlinks is 'False', and both src and dst are symbolic links, copymode() will attempt to modify the mode
    of dst itself (rather than the file it points to).

    This function supports src and dst being either a local or UNC path. A relative path will be resolved based on the
    current working directory.

    :param src: The src file or directory to copy the read only flag from.
    :param dst: The dst file or directory to copy the read only flag to.
    :param follow_symlinks: Whether to copy the read only flag on the symlink or the target of the symlink.
    :param kwargs: Common arguments used to build the SMB Session for any UNC paths.
    """
    src_mode = stat.S_IMODE(_get_file_stat(src, follow_symlinks, **kwargs).st_mode)

    norm_dst = ntpath.normpath(dst)
    if norm_dst.startswith('\\\\'):
        read_only = not (src_mode & stat.S_IWRITE == stat.S_IWRITE and src_mode & stat.S_IREAD == stat.S_IREAD)
        _set_file_basic_info(dst, follow_symlinks, read_only=read_only, **kwargs)
    else:
        _local_chmod(dst, src_mode, follow_symlinks) 
示例2
def readlink(path, **kwargs):
    """
    Return a string representing the path to which the symbolic link points. If the link is relative it will be
    converted to an absolute pathname relative to the link itself. The link target may point to a local path and not
    another UNC path.

    :param path: The path to the symbolic link to read.
    :param kwargs: Common SMB Session arguments for smbclient.
    :return: The link target path.
    """
    norm_path = ntpath.normpath(path)
    reparse_buffer = _get_reparse_point(norm_path, **kwargs)
    reparse_tag = reparse_buffer['reparse_tag']
    if reparse_tag.get_value() != ReparseTags.IO_REPARSE_TAG_SYMLINK:
        raise ValueError(to_native("Cannot read link of reparse point with tag %s at '%s'" % (str(reparse_tag),
                                                                                              norm_path)))

    symlink_buffer = SymbolicLinkReparseDataBuffer()
    symlink_buffer.unpack(reparse_buffer['data_buffer'].get_value())
    return symlink_buffer.resolve_link(norm_path) 
示例3
def removedirs(name, **kwargs):
    """
    Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed,
    removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which
    is ignored, because it generally means that a parent directory is not empty).

    :param name: The directory to start removing recursively from.
    :param kwargs: Common SMB Session arguments for smbclient.
    """
    remove_dir = ntpath.normpath(name)
    while True:
        try:
            rmdir(remove_dir, **kwargs)
        except (SMBResponseException, OSError):
            return
        else:
            remove_dir = ntpath.dirname(remove_dir) 
示例4
def _rename_information(src, dst, replace_if_exists=False, **kwargs):
    verb = 'replace' if replace_if_exists else 'rename'
    norm_src = ntpath.normpath(src)
    norm_dst = ntpath.normpath(dst)

    if not norm_dst.startswith('\\\\'):
        raise ValueError("dst must be an absolute path to where the file or directory should be %sd." % verb)

    src_root = ntpath.splitdrive(norm_src)[0]
    dst_root, dst_name = ntpath.splitdrive(norm_dst)
    if src_root.lower() != dst_root.lower():
        raise ValueError("Cannot %s a file to a different root than the src." % verb)

    raw = SMBRawIO(src, mode='r', share_access='rwd', desired_access=FilePipePrinterAccessMask.DELETE,
                   create_options=CreateOptions.FILE_OPEN_REPARSE_POINT, **kwargs)
    with SMBFileTransaction(raw) as transaction:
        file_rename = FileRenameInformation()
        file_rename['replace_if_exists'] = replace_if_exists
        file_rename['file_name'] = to_text(dst_name[1:])  # dst_name has \ prefix from splitdrive, we remove that.
        set_info(transaction, file_rename) 
示例5
def test_copyfile_symlink_dont_follow(smb_share):
    src_filename = "%s\\source.txt" % smb_share
    src_link = "%s\\source-link.txt" % smb_share
    dst_filename = "%s\\target.txt" % smb_share

    with open_file(src_filename, mode='w') as fd:
        fd.write(u"content")

    symlink(src_filename, src_link)
    actual = copyfile(src_link, dst_filename, follow_symlinks=False)
    assert actual == dst_filename

    with open_file(dst_filename, mode='r') as fd:
        assert fd.read() == u"content"

    assert islink(dst_filename)
    assert readlink(dst_filename) == ntpath.normpath(src_filename) 
示例6
def mkdir(self, shareName, pathName, password = None):
        # ToDo: Handle situations where share is password protected
        pathName = string.replace(pathName,'/', '\\')
        pathName = ntpath.normpath(pathName)
        if len(pathName) > 0 and pathName[0] == '\\':
            pathName = pathName[1:]

        treeId = self.connectTree(shareName)

        fileId = None
        try:
            fileId = self.create(treeId, pathName,GENERIC_ALL ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_CREATE, 0)          
        finally:
            if fileId is not None:
                self.close(treeId, fileId)            
            self.disconnectTree(treeId) 

        return True 
示例7
def rmdir(self, shareName, pathName, password = None):
        # ToDo: Handle situations where share is password protected
        pathName = string.replace(pathName,'/', '\\')
        pathName = ntpath.normpath(pathName)
        if len(pathName) > 0 and pathName[0] == '\\':
            pathName = pathName[1:]

        treeId = self.connectTree(shareName)

        fileId = None
        try:
            fileId = self.create(treeId, pathName, desiredAccess=DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
                                 shareMode=FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
                                 creationOptions=FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT,
                                 creationDisposition=FILE_OPEN, fileAttributes=0)
            from impacket import smb
            delete_req = smb.SMBSetFileDispositionInfo()
            delete_req['DeletePending'] = True
            self.setInfo(treeId, fileId, inputBlob=delete_req, fileInfoClass=SMB2_FILE_DISPOSITION_INFO)
        finally:
            if fileId is not None:
                self.close(treeId, fileId)
            self.disconnectTree(treeId) 

        return True 
示例8
def remove(self, shareName, pathName, password = None):
        # ToDo: Handle situations where share is password protected
        pathName = string.replace(pathName,'/', '\\')
        pathName = ntpath.normpath(pathName)
        if len(pathName) > 0 and pathName[0] == '\\':
            pathName = pathName[1:]

        treeId = self.connectTree(shareName)

        fileId = None
        try:
            fileId = self.create(treeId, pathName,DELETE | FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE, FILE_OPEN, 0)
        finally:
            if fileId is not None:
                self.close(treeId, fileId)
            self.disconnectTree(treeId) 

        return True 
示例9
def storeFile(self, shareName, path, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_WRITE):
        # ToDo: Handle situations where share is password protected
        path = string.replace(path,'/', '\\')
        path = ntpath.normpath(path)
        if len(path) > 0 and path[0] == '\\':
            path = path[1:]

        treeId = self.connectTree(shareName)
        fileId = None
        try:
            fileId = self.create(treeId, path, FILE_WRITE_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0)
            finished = False
            writeOffset = offset
            while not finished:
                data = callback(self._Connection['MaxWriteSize'])
                if len(data) == 0:
                    break
                written = self.write(treeId, fileId, data, writeOffset, len(data))
                writeOffset += written
        finally:
            if fileId is not None:
                self.close(treeId, fileId)
            self.disconnectTree(treeId) 
示例10
def printSources(self, hierarchy, commonprefix):
        sorteditems = sorted(hierarchy.items(), key=lambda a: a[0].lower())

        # First folders, then files
        for key, value in sorteditems:
            if SCons.Util.is_Dict(value):
                self.file.write('\t\t\t<Filter\n'
                                '\t\t\t\tName="%s"\n'
                                '\t\t\t\tFilter="">\n' % (key))
                self.printSources(value, commonprefix)
                self.file.write('\t\t\t</Filter>\n')

        for key, value in sorteditems:
            if SCons.Util.is_String(value):
                file = value
                if commonprefix:
                    file = os.path.join(commonprefix, value)
                file = os.path.normpath(file)
                self.file.write('\t\t\t<File\n'
                                '\t\t\t\tRelativePath="%s">\n'
                                '\t\t\t</File>\n' % (file)) 
示例11
def printSources(self, hierarchy, kind, commonprefix, filter_name):
        keywords = {'Source Files': 'ClCompile',
                    'Header Files': 'ClInclude',
                    'Local Headers': 'ClInclude',
                    'Resource Files': 'None',
                    'Other Files': 'None'}

        sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower())

        # First folders, then files
        for key, value in sorteditems:
            if SCons.Util.is_Dict(value):
                self.printSources(value, kind, commonprefix, filter_name + '\\' + key)

        for key, value in sorteditems:
            if SCons.Util.is_String(value):
                file = value
                if commonprefix:
                    file = os.path.join(commonprefix, value)
                file = os.path.normpath(file)

                self.file.write('\t\t<%s Include="%s" />\n' % (keywords[kind], file))
                self.filters_file.write('\t\t<%s Include="%s">\n'
                                        '\t\t\t<Filter>%s</Filter>\n'
                                        '\t\t</%s>\n' % (keywords[kind], file, filter_name, keywords[kind])) 
示例12
def printSources(self, hierarchy, commonprefix):
        sorteditems = sorted(hierarchy.items(), key=lambda a: a[0].lower())

        # First folders, then files
        for key, value in sorteditems:
            if SCons.Util.is_Dict(value):
                self.file.write('\t\t\t<Filter\n'
                                '\t\t\t\tName="%s"\n'
                                '\t\t\t\tFilter="">\n' % (key))
                self.printSources(value, commonprefix)
                self.file.write('\t\t\t</Filter>\n')

        for key, value in sorteditems:
            if SCons.Util.is_String(value):
                file = value
                if commonprefix:
                    file = os.path.join(commonprefix, value)
                file = os.path.normpath(file)
                self.file.write('\t\t\t<File\n'
                                '\t\t\t\tRelativePath="%s">\n'
                                '\t\t\t</File>\n' % (file)) 
示例13
def printSources(self, hierarchy, kind, commonprefix, filter_name):
        keywords = {'Source Files': 'ClCompile',
                    'Header Files': 'ClInclude',
                    'Local Headers': 'ClInclude',
                    'Resource Files': 'None',
                    'Other Files': 'None'}
                    
        sorteditems = sorted(hierarchy.items(), key = lambda a: a[0].lower())

        # First folders, then files
        for key, value in sorteditems:
            if SCons.Util.is_Dict(value):
                self.printSources(value, kind, commonprefix, filter_name + '\\' + key)

        for key, value in sorteditems:
            if SCons.Util.is_String(value):
                file = value
                if commonprefix:
                    file = os.path.join(commonprefix, value)
                file = os.path.normpath(file)
                
                self.file.write('\t\t<%s Include="%s" />\n' % (keywords[kind], file))
                self.filters_file.write('\t\t<%s Include="%s">\n'
                                        '\t\t\t<Filter>%s</Filter>\n'
                                        '\t\t</%s>\n' % (keywords[kind], file, filter_name, keywords[kind])) 
示例14
def _generateGUID(slnfile, name):
    """This generates a dummy GUID for the sln file to use.  It is
    based on the MD5 signatures of the sln filename plus the name of
    the project.  It basically just needs to be unique, and not
    change with each invocation."""
    m = hashlib.md5()
    # Normalize the slnfile path to a Windows path (\ separators) so
    # the generated file has a consistent GUID even if we generate
    # it on a non-Windows platform.
    m.update(ntpath.normpath(str(slnfile)) + str(name))
    # TODO(1.5)
    #solution = m.hexdigest().upper()
    solution = string.upper(_hexdigest(m.digest()))
    # convert most of the signature to GUID form (discard the rest)
    solution = "{" + solution[:8] + "-" + solution[8:12] + "-" + solution[12:16] + "-" + solution[16:20] + "-" + solution[20:32] + "}"
    return solution 
示例15
def printSources(self, hierarchy, commonprefix):
        sorteditems = hierarchy.items()
        # TODO(1.5):
        #sorteditems.sort(lambda a, b: cmp(a[0].lower(), b[0].lower()))
        sorteditems.sort(lambda a, b: cmp(string.lower(a[0]), string.lower(b[0])))

        # First folders, then files
        for key, value in sorteditems:
            if SCons.Util.is_Dict(value):
                self.file.write('\t\t\t<Filter\n'
                                '\t\t\t\tName="%s"\n'
                                '\t\t\t\tFilter="">\n' % (key))
                self.printSources(value, commonprefix)
                self.file.write('\t\t\t</Filter>\n')

        for key, value in sorteditems:
            if SCons.Util.is_String(value):
                file = value
                if commonprefix:
                    file = os.path.join(commonprefix, value)
                file = os.path.normpath(file)
                self.file.write('\t\t\t<File\n'
                                '\t\t\t\tRelativePath="%s">\n'
                                '\t\t\t</File>\n' % (file)) 
示例16
def __init__(self, dswfile, source, env):
        self.dswfile = os.path.normpath(str(dswfile))
        self.env = env

        if 'projects' not in env:
            raise SCons.Errors.UserError("You must specify a 'projects' argument to create an MSVSSolution.")
        projects = env['projects']
        if not SCons.Util.is_List(projects):
            raise SCons.Errors.InternalError("The 'projects' argument must be a list of nodes.")
        projects = SCons.Util.flatten(projects)
        if len(projects) < 1:
            raise SCons.Errors.UserError("You must specify at least one project to create an MSVSSolution.")
        self.dspfiles = map(str, projects)

        if 'name' in self.env:
            self.name = self.env['name']
        else:
            self.name = os.path.basename(SCons.Util.splitext(self.dswfile)[0])
        self.name = self.env.subst(self.name) 
示例17
def mkdir(self, shareName, pathName, password = None):
        # ToDo: Handle situations where share is password protected
        pathName = string.replace(pathName,'/', '\\')
        pathName = ntpath.normpath(pathName)
        if len(pathName) > 0 and pathName[0] == '\\':
            pathName = pathName[1:]

        treeId = self.connectTree(shareName)

        fileId = None
        try:
            fileId = self.create(treeId, pathName,GENERIC_ALL ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_CREATE, 0)          
        finally:
            if fileId is not None:
                self.close(treeId, fileId)            
            self.disconnectTree(treeId) 

        return True 
示例18
def rmdir(self, shareName, pathName, password = None):
        # ToDo: Handle situations where share is password protected
        pathName = string.replace(pathName,'/', '\\')
        pathName = ntpath.normpath(pathName)
        if len(pathName) > 0 and pathName[0] == '\\':
            pathName = pathName[1:]

        treeId = self.connectTree(shareName)

        fileId = None
        try:
            fileId = self.create(treeId, pathName, desiredAccess=DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE,
                                 shareMode=FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
                                 creationOptions=FILE_DIRECTORY_FILE | FILE_OPEN_REPARSE_POINT,
                                 creationDisposition=FILE_OPEN, fileAttributes=0)
            from impacket import smb
            delete_req = smb.SMBSetFileDispositionInfo()
            delete_req['DeletePending'] = True
            self.setInfo(treeId, fileId, inputBlob=delete_req, fileInfoClass=SMB2_FILE_DISPOSITION_INFO)
        finally:
            if fileId is not None:
                self.close(treeId, fileId)
            self.disconnectTree(treeId) 

        return True 
示例19
def remove(self, shareName, pathName, password = None):
        # ToDo: Handle situations where share is password protected
        pathName = string.replace(pathName,'/', '\\')
        pathName = ntpath.normpath(pathName)
        if len(pathName) > 0 and pathName[0] == '\\':
            pathName = pathName[1:]

        treeId = self.connectTree(shareName)

        fileId = None
        try:
            fileId = self.create(treeId, pathName,DELETE | FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE, FILE_NON_DIRECTORY_FILE | FILE_DELETE_ON_CLOSE, FILE_OPEN, 0)
        finally:
            if fileId is not None:
                self.close(treeId, fileId)
            self.disconnectTree(treeId) 

        return True 
示例20
def storeFile(self, shareName, path, callback, mode = FILE_OVERWRITE_IF, offset = 0, password = None, shareAccessMode = FILE_SHARE_WRITE):
        # ToDo: Handle situations where share is password protected
        path = string.replace(path,'/', '\\')
        path = ntpath.normpath(path)
        if len(path) > 0 and path[0] == '\\':
            path = path[1:]

        treeId = self.connectTree(shareName)
        fileId = None
        try:
            fileId = self.create(treeId, path, FILE_WRITE_DATA, shareAccessMode, FILE_NON_DIRECTORY_FILE, mode, 0)
            finished = False
            writeOffset = offset
            while not finished:
                data = callback(self._Connection['MaxWriteSize'])
                if len(data) == 0:
                    break
                written = self.write(treeId, fileId, data, writeOffset, len(data))
                writeOffset += written
        finally:
            if fileId is not None:
                self.close(treeId, fileId)
            self.disconnectTree(treeId) 
示例21
def _parse_unix(cls, volume_config):
        parts = volume_config.split(':')

        if len(parts) > 3:
            raise ConfigurationError(
                "Volume %s has incorrect format, should be "
                "external:internal[:mode]" % volume_config)

        if len(parts) == 1:
            external = None
            internal = os.path.normpath(parts[0])
        else:
            external = os.path.normpath(parts[0])
            internal = os.path.normpath(parts[1])

        mode = 'rw'
        if len(parts) == 3:
            mode = parts[2]

        return cls(external, internal, mode) 
示例22
def do_get(self, src_path):

        try:
            import ntpath
            newPath = ntpath.normpath(ntpath.join(self.__pwd, src_path))
            drive, tail = ntpath.splitdrive(newPath) 
            filename = ntpath.basename(tail)
            fh = open(filename,'wb')
            self.__transferClient.getFile(drive[:-1]+'$', tail, fh.write)
            fh.close()

        except Exception as e:
            logging.error(str(e))

            if os.path.exists(filename):
                os.remove(filename) 
示例23
def do_get(self, src_path):

        try:
            import ntpath
            newPath = ntpath.normpath(ntpath.join(self.__pwd, src_path))
            drive, tail = ntpath.splitdrive(newPath) 
            filename = ntpath.basename(tail)
            fh = open(filename,'wb')
            self.__transferClient.getFile(drive[:-1]+'$', tail, fh.write)
            fh.close()

        except Exception as e:
            logging.error(str(e))

            if os.path.exists(filename):
                os.remove(filename) 
示例24
def upload_file(self, host, src, dst):
        dst = dst.replace('/','\\')
        dst = ntpath.normpath(dst)
        dst = dst.split('\\')
        share = dst[0]
        dst = '\\'.join(dst[1:])
        if os.path.exists(src):
            print('[+] Starting upload: %s (%s bytes)' % (src, os.path.getsize(src)))
            upFile = open(src, 'rb')
            try:
                self.smbconn[host].putFile(share, dst, upFile.read)
                print('[+] Upload complete')
            except Exception as e:
                print('[!]', e)
                print('[!] Error uploading file, you need to include destination file name in the path')
            upFile.close()
        else:
            print('[!] Invalid source. File does not exist')
            sys.exit() 
示例25
def printSources(self, hierarchy, commonprefix):
        sorteditems = sorted(hierarchy.items(), key=lambda a: a[0].lower())

        # First folders, then files
        for key, value in sorteditems:
            if SCons.Util.is_Dict(value):
                self.file.write('\t\t\t<Filter\n'
                                '\t\t\t\tName="%s"\n'
                                '\t\t\t\tFilter="">\n' % (key))
                self.printSources(value, commonprefix)
                self.file.write('\t\t\t</Filter>\n')

        for key, value in sorteditems:
            if SCons.Util.is_String(value):
                file = value
                if commonprefix:
                    file = os.path.join(commonprefix, value)
                file = os.path.normpath(file)
                self.file.write('\t\t\t<File\n'
                                '\t\t\t\tRelativePath="%s">\n'
                                '\t\t\t</File>\n' % (file)) 
示例26
def copystat(src, dst, follow_symlinks=True, **kwargs):
    """
    Copy the read only attribute, last access time, and last modification time from src to dst. The file contents,
    owner, and group are unaffected.

    If follow_symlinks is 'False' and src and dst both refer to symbolic links, copystat() will operate on the
    symbolic links themselves rather than the files the symbolic links refer to.

    :param src: The src file or directory to copy the read only flag from.
    :param dst: The dst file or directory to copy the read only flag to.
    :param follow_symlinks: Whether to copy the read only flag on the symlink or the target of the symlink.
    :param kwargs: Common arguments used to build the SMB Session for any UNC paths.
    """
    src_stat = _get_file_stat(src, follow_symlinks, **kwargs)
    src_mode = stat.S_IMODE(src_stat.st_mode)

    # *_ns was only added in Python 3, fallback to a manual calculation from seconds since EPOCH.
    atime_ns = getattr(src_stat, 'st_atime_ns', src_stat.st_atime * 1000000000)
    mtime_ns = getattr(src_stat, 'st_mtime_ns', src_stat.st_mtime * 1000000000)

    norm_dst = ntpath.normpath(dst)
    if norm_dst.startswith('\\\\'):
        read_only = not (src_mode & stat.S_IWRITE == stat.S_IWRITE and src_mode & stat.S_IREAD == stat.S_IREAD)
        _set_file_basic_info(dst, follow_symlinks, read_only=read_only, atime_ns=atime_ns, mtime_ns=mtime_ns, **kwargs)
    else:
        if not follow_symlinks and sys.version_info[0] < 3:
            # Python 2 always follows symlinks and does not have a kwarg to override, we can only just fail here.
            raise NotImplementedError("utime: follow_symlinks unavailable on this platform")

        _local_chmod(dst, src_mode, follow_symlinks)

        if sys.version_info[0] < 3:
            os.utime(dst, (atime_ns / 1000000000, mtime_ns / 1000000000))
        else:
            os.utime(dst, ns=(atime_ns, mtime_ns), follow_symlinks=follow_symlinks) 
示例27
def _copy(src, dst, follow_symlinks, copy_meta_func, **kwargs):
    # Need to check if dst is a UNC path before checking if it's a dir in smbclient.path before checking to see if it's
    # a local directory. If either one is a dir, join the filename of src onto dst.
    if ntpath.normpath(dst).startswith('\\\\') and isdir(dst, **kwargs):
        dst = ntpath.join(dst, ntpath.basename(src))
    elif os.path.isdir(dst):
        dst = os.path.join(dst, os.path.basename(src))

    copyfile(src, dst, follow_symlinks=follow_symlinks)
    copy_meta_func(src, dst, follow_symlinks=follow_symlinks)
    return dst 
示例28
def get_smb_tree(path, username=None, password=None, port=445, encrypt=None, connection_timeout=60,
                 connection_cache=None):
    """
    Returns an active Tree connection and file path including the tree based on the UNC path passed in and other
    connection arguments. The opened connection is registered in a pool and re-used if a connection is made to the same
    server with the same credentials.

    :param path: The absolute UNC path we want to open a tree connect to.
    :param username: Optional username to connect with. Required if no session has been registered for the server and
        Kerberos auth is not being used.
    :param password: Optional password to connect with.
    :param port: The port to connect with.
    :param encrypt: Whether to force encryption or not, once this has been set to True the session cannot be changed
        back to False.
    :param connection_timeout: Override the timeout used for the initial connection.
    :param connection_cache: Connection cache to be used with
    :return: The TreeConnect and file path including the tree based on the UNC path passed in.
    """
    path_split = [p for p in ntpath.normpath(path).split("\\") if p]
    if len(path_split) < 2:
        raise ValueError("The SMB path specified must contain the server and share to connect to")

    server = path_split[0]
    share_path = "\\\\%s\\%s" % (server, path_split[1])

    session = register_session(server, username=username, password=password, port=port, encrypt=encrypt,
                               connection_timeout=connection_timeout, connection_cache=connection_cache)

    tree = next((t for t in session.tree_connect_table.values() if t.share_name == share_path), None)
    if not tree:
        tree = TreeConnect(session, share_path)
        tree.connect()

    file_path = ""
    if len(path_split) > 2:
        file_path = "\\".join(path_split[2:])

    return tree, file_path 
示例29
def link(src, dst, follow_symlinks=True, **kwargs):
    """
    Create a hard link pointing to src named dst. The src argument must be an absolute path in the same share as
    src.

    :param src: The full UNC path to used as the source of the hard link.
    :param dst: The full UNC path to create the hard link at.
    :param follow_symlinks: Whether to link to the src target (True) or src itself (False) if src is a symlink.
    :param kwargs: Common arguments used to build the SMB Session.
    """
    norm_src = ntpath.normpath(src)
    norm_dst = ntpath.normpath(dst)

    if not norm_src.startswith('\\\\'):
        raise ValueError("src must be the absolute path to where the file is hard linked to.")

    src_root = ntpath.splitdrive(norm_src)[0]
    dst_root, dst_name = ntpath.splitdrive(norm_dst)
    if src_root.lower() != dst_root.lower():
        raise ValueError("Cannot hardlink a file to a different root than the src.")

    raw = SMBFileIO(norm_src, mode='r', share_access='rwd',
                    desired_access=FilePipePrinterAccessMask.FILE_WRITE_ATTRIBUTES,
                    create_options=0 if follow_symlinks else CreateOptions.FILE_OPEN_REPARSE_POINT, **kwargs)
    with SMBFileTransaction(raw) as transaction:
        link_info = FileLinkInformation()
        link_info['replace_if_exists'] = False
        link_info['file_name'] = to_text(dst_name[1:])
        set_info(transaction, link_info) 
示例30
def test_copytree_with_symlink_and_flag(smb_share):
    src_dirname = "%s\\source" % smb_share
    dst_dirname = "%s\\target" % smb_share

    makedirs("%s\\dir" % src_dirname)
    symlink("%s\\dir" % src_dirname, "%s\\link" % src_dirname)

    with open_file("%s\\file.txt" % src_dirname, mode='w') as fd:
        fd.write(u"content")
    symlink("%s\\file.txt" % src_dirname, "%s\\link.txt" % src_dirname)

    with open_file("%s\\dir\\file.txt" % src_dirname, mode='w') as fd:
        fd.write(u"content")

    actual = copytree(src_dirname, dst_dirname, symlinks=True)
    assert actual == dst_dirname

    assert islink("%s\\link" % dst_dirname)
    assert ntpath.normpath(readlink("%s\\link" % dst_dirname)) == ntpath.normpath("%s\\dir" % src_dirname)
    assert samefile("%s\\link\\file.txt" % dst_dirname, "%s\\dir\\file.txt" % src_dirname)
    assert not samefile("%s\\link\\file.txt" % dst_dirname, "%s\\dir\\file.txt" % dst_dirname)

    assert islink("%s\\link.txt" % dst_dirname)
    assert ntpath.normpath(readlink("%s\\link.txt" % dst_dirname)) == ntpath.normpath("%s\\file.txt" % src_dirname)
    assert samefile("%s\\link.txt" % dst_dirname, "%s\\file.txt" % src_dirname)
    assert not samefile("%s\\link.txt" % dst_dirname, "%s\\file.txt" % dst_dirname)