Checking File Permissions in Linux with Python

Python

Python Problem Overview


I'm writing a script to check permissions of files in user's directories and if they're not acceptable I'll be warning them, but I want to check permissions of not just the logged in user, but also group and others. How can i do this? It seems to me that os.access() in Python can only check the permissions for the user running the script.

Python Solutions


Solution 1 - Python

You're right that os.access, like the underlying access syscall, checks for a specific user (real rather than effective IDs, to help out with suid situations).

os.stat is the right way to get more general info about a file, including permissions per user, group, and others. The st_mode attribute of the object that os.stat returns has the permission bits for the file.

To help interpret those bits, you may want to use the stat module. Specifically, you'll want the bitmasks defined here, and you'll use the & operator (bit-and) to use them to mask out the relevant bits in that st_mode attribute -- for example, if you just need a True/False check on whether a certain file is group-readable, one approach is:

import os
import stat

def isgroupreadable(filepath):
  st = os.stat(filepath)
  return bool(st.st_mode & stat.S_IRGRP)

Take care: the os.stat call can be somewhat costly, so make sure to extract all info you care about with a single call, rather than keep repeating calls for each bit of interest;-).

Solution 2 - Python

Just to help other people like me who came here for something a bit different :

import os
import stat

st = os.stat(yourfile)
oct_perm = oct(st.st_mode)
print(oct_perm)
# -> 0o100664

The last 3 or 4 digits is probably what you want.

See this for more details: https://stackoverflow.com/a/5337329/1814774

Solution 3 - Python

You can check file permissions via os.stat(path) in conjunction with the stat module for interpreting the results.

Solution 4 - Python

import os
os.access('my_file', os.R_OK) # Check for read access
os.access('my_file', os.W_OK) # Check for write access
os.access('my_file', os.X_OK) # Check for execution access
os.access('my_file', os.F_OK) # Check for existence of file

Solution 5 - Python

Use os.access() with flags os.R_OK, os.W_OK, and os.X_OK.

Edit: Check out this related question if you are testing directory permissions on Windows.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJon PhenowView Question on Stackoverflow
Solution 1 - PythonAlex MartelliView Answer on Stackoverflow
Solution 2 - PythonPobeView Answer on Stackoverflow
Solution 3 - PythonmikuView Answer on Stackoverflow
Solution 4 - PythonOneOfAKind_12View Answer on Stackoverflow
Solution 5 - PythonParappaView Answer on Stackoverflow