How to get linux direcory/file permission string using python

Question:

I need to get permission string like drwxr-xr-x, drwxrwxr-x in python:

 drwxr-xr-x 2 root root 4.0K Dec 12 18:46 mount_test2
 drwxrwxr-x 2 root root 4.0K Dec 12 18:47 mount_test
Asked By: Jamshy

||

Answers:

You could use the subprocess module and get the answer like this:

from subprocess import Popen, PIPE
p = Popen(['ls', '-l', 'path/to/your/dir'], stdout = PIPE, stderr = PIPE)
out, err = p.communicate()

Your out variable will contain the answer you want and you can process it like this:

for elem in out.split('n'):
    permission = elem.split(' ')[0]

but there are many ways to process the strings you get in your output.

NOTE FOR PYTHON3: the output needs to be decoded before:

out = out.decode('utf-8')
Answered By: toti08

what you are really looking for is sth. like this:

stats_flags = [
    (stat.S_IRUSR, "r"),
    (stat.S_IWUSR, "w"),
    (stat.S_IXUSR, "x"),
    (stat.S_IRGRP, "r"),
    (stat.S_IWGRP, "w"),
    (stat.S_IXGRP, "x"),
    (stat.S_IROTH, "r"),
    (stat.S_IWOTH, "w"),
    (stat.S_IXOTH, "x"),
]

def get_permission_string_of_item(itempath):
    perms = os.stat(itempath).st_mode
    perm_string = ""
    for stats in stats_flags:
        if stats[0] and perms:
            perm_string += stats[1]
        else:
            perm_string += "-"

    return perm_string
Answered By: Nikolai Ehrhardt
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.