Check if the path is accessible to a non-root user

I have a setup script written in Python (on Linux) that runs as root and needs to check if certain files are read by a non-root user.

For this reason, I cannot use os.path.exists () or open (filename) (and catch any exceptions).

I'm currently going to check the permission bits on each file, but the only problem is that I have to check the permission bits in the path leading to the file name (directories need r + x bits set), which can be a very slow process if I have thousands of files.

Is my solution the best, or are there better alternatives?

edit: I need the script to run as root after checking the files, so giving up root privileges is not unfortunately.

+6
source share
1 answer

You can use os.seteuid to change the effective user for some non-root user. Then try to open the file. IOError will be raised if permission is denied.

 import os os.seteuid(65534) # user 65534 is `nobody` filename='/etc/passwd-' try: open(filename,'r') except IOError as err: print(err) # [Errno 13] Permission denied: '/etc/passwd-' 
+4
source

Source: https://habr.com/ru/post/892336/


All Articles