In python I can check whether my own user can access a file or directory using os.access
. However, is it possible check whether another user can do so?
One possibility is to check the user's uid and groups against the permissions on the file:
import os, grp, pwd, stat
def user_access(uid, path, perms=os.R_OK | os.W_OK):
stats = os.stat(path)
# other users
if stats.st_mode & perms == perms:
return True
# owner
if stats.st_uid == uid and (stats.st_mode >> 6) & perms == perms:
return True
# group
user = pwd.getpwuid(uid).pw_name
if (stats.st_mode >> 3) & perms == perms and user in grp.getgrgid(stats.st_gid).gr_mem:
return True
return False
However, I guess this is specific to POSIX systems and I could imagine there would be edge cases it fails on. In fact, the libc manual on access
specifically warns against this solution:
There is another way you could check this access, which is ... to examine the file mode bits and mimic the system’s own access computation. This method is undesirable because many systems have additional access control features; your program cannot portably mimic them, and you would not want to try to keep track of the diverse features that different systems have. Using access is simple and automatically does whatever is appropriate for the system you are using.
Is there a more concise and/or robust solution for checking access of other users?
Edit 2020-12-09: Fixed bugs with the bit twiddling.