javex
javex

Reputation: 7544

How to convert a stat output to a unix permissions string

If you run os.stat(path) on a file and then take its st_mode parameter, how do you get from there to a string like this: rw-r--r-- as known from the Unix world?

Upvotes: 9

Views: 8482

Answers (3)

awesoon
awesoon

Reputation: 33671

Since Python 3.3 you could use stat.filemode:

In [7]: import os, stat

In [8]: print(stat.filemode(os.stat('/home/soon/foo').st_mode))
-rw-r--r--

In [9]: ls -l ~/foo
-rw-r--r-- 1 soon users 0 Jul 23 18:15 /home/soon/foo

Upvotes: 16

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

Something like this:

import stat, os
def permissions_to_unix_name(st):
    is_dir = 'd' if stat.S_ISDIR(st.st_mode) else '-'
    dic = {'7':'rwx', '6' :'rw-', '5' : 'r-x', '4':'r--', '0': '---'}
    perm = str(oct(st.st_mode)[-3:])
    return is_dir + ''.join(dic.get(x,x) for x in perm)
... 

>>> permissions_to_unix_name(os.stat('.'))
'drwxr-xr-x'
>>> ls -ld .
drwxr-xr-x 62 monty monty 4096 Jul 23 13:23 ./

>>> permissions_to_unix_name(os.stat('so.py'))
'-rw-rw-r--'
>>> ls -ld so.py
-rw-rw-r-- 1 monty monty 68 Jul 18 15:57 so.py

Upvotes: 6

javex
javex

Reputation: 7544

The following function will achieve this, given some usual circumstances (i.e. I haven't tested it under Windows or with SELinux).

import stat
def permissions_to_unix_name(st_mode):
    permstr = ''
    usertypes = ['USR', 'GRP', 'OTH']
    for usertype in usertypes:
        perm_types = ['R', 'W', 'X']
        for permtype in perm_types:
            perm = getattr(stat, 'S_I%s%s' % (permtype, usertype))
            if st_mode & perm:
                permstr += permtype.lower()
            else:
                permstr += '-'
    return permstr

This produces a basic string as asked. However, this could also be improved to display further data, e.g. whether it is a directory (d) or a symlink (l). Feel free to improve it.

Upvotes: 2

Related Questions