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
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')
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
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
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')
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