Search code examples
pythonlinuxfat32

Get fat32 attributes with python


How i can get fat32 attributes (like archived, hidden...) in linux without spawning a new process with fatattr utility call ? May be there is python binding for it or for linux/fs functions (fat_ioctl_get_attributes, http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/fs/fat/file.c). Or maybe it can be done with python-xattr ?


Solution

  • As you can see in the function name, the kernel function fat_ioctl_get_attributes is called from userspace via an ioctl, and I'm not aware of any other binding. Therefore, you can simply read the attributes by calling ioctl yourself, like this:

    import array
    import fcntl
    import os
    
    FAT_IOCTL_GET_ATTRIBUTES = 0x80047210
    FATATTR_BITS = 'rhsvda67'
    
    def get_fat_attrs(fn):
        fd = os.open(fn, os.O_RDONLY)
        try:
            buf = array.array('L', [0])
            try:
                fcntl.ioctl(fd, FAT_IOCTL_GET_ATTRIBUTES, buf, True)
            except IOError as ioe:
                if ioe.errno == 25: # Not a FAT volume
                    return None
                else:
                    raise
    
            return buf[0]
        finally:
            os.close(fd)
    
    if __name__ == '__main__':
        import sys
        for fn in sys.argv[1:]:
            attrv = get_fat_attrs(fn)
            if attrv is None:
                print(fn + ': Not on a FAT volume')
                continue
            s = ''.join((fb if (1 << idx) & attrv else ' ')
                        for idx,fb in enumerate(FATATTR_BITS))
            print(fn + ': ' + s)