Checking file permissions on Linux using Python

I am writing a script to check the permissions of files in user directories, and if they are unacceptable, I will warn them, but I want to check the permissions of not only the logged-in user, but also groups and others. How can i do this? It seems to me that os.access() in Python can only check permissions for the user running the script.

+57
python
Dec 07 '09 at 18:10
source share
6 answers

You are correct that os.access , as basic access , checks for a specific user (real and not effective identifiers to deal with suid situations).

os.stat is the right way to get more general information about a file, including permissions for each user, group, and others. The st_mode attribute of the object returned by os.stat has a permission bit for the file.

To interpret these bits, you can use the stat module. In particular, you want the bitmasks to be defined here , and you will use the & operator (bits) to use them to mask the corresponding bits in this st_mode attribute - for example, if you just need a True / False check, is there a specific file available for the group, one approach:

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

Take care: calling os.stat can be a little expensive, so be sure to retrieve all the information you care about with a single call, rather than repeating calls for each piece of interest; -).

+91
Dec 07 '09 at 18:31
source share
β€” -

You can check file permissions via os.stat(path) in combination with stat to interpret the results.

+9
Dec 07 '09 at 18:15
source share

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

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

+8
Dec 07 '09 at 18:13
source share

Just to help other people like me who came here for something else:

 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: stack overflow

+6
Aug 08 '17 at 18:37
source share

os.stat and the associated mask bit for the mode.

+3
Dec 07 '09 at 18:20
source share
 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 
0
Jun 24 '19 at 20:02
source share



All Articles