I have an interesting scenario that I would like to get some expert advice on implementing. I have a Python application running on Linux that needs to return a single directory based upon group permissions.
For example, the Linux filesystem looks like this:
/Directory/Apple
/Directory/Beta
/Directory/Carotene
There is a group in /etc/group for Apple, Beta, and Carotene. Those group permissions are assigned to each directory (the Apple directory is only viewable/executable by members of the Apple group etc). A logged in user can only be a member of one group (Apple/Beta/Carotene), and I need to be able to figure out which directory the user has access to without throwing an exception. I can't use group membership calls inside of Python as the directory structure above is a remotely mounted filesystem.
So to simplify this: if the user is a member of the Beta group, I need to stat each subdir inside of /Directory and then return only a single path (in this example /Directory/Beta as the user is a member of the group directory).
I am thinking os.stat is a good way of doing this but I would like to see some other implementations if possible.
Thanks in advance!
To determine if a particular directory is accessible, use os.access
.
os.access('/Directory/Apple', os.R_OK)
To check all of the immediate subdirs of /Directory
, try this loop:
def find_my_group_directory():
#UNTESTED
root, dirs, _ = next(os.walk('/Directory'))
for dir in dirs:
if os.access(os.path.join(root, dir), os.R_OK):
return os.path.join(root, dir)
return None
It's easier to ask forgiveness than permission ( EAFP ). To check if a directory is accessible:
import os
def accessible(dir):
try:
os.listdir(dir)
except OSError:
return False
return True
print(accessible('/root'))
To check if all the subdirs of a directory are permitted or not, apply this function in a for
loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.