在python我们要判断一个文件对当前用户有没有读、写、执行权限,我们通常可以使用os.access函数来实现,比如:
# 判断读权限
os.access(, os.r_ok)
# 判断写权限
os.access(, os.w_ok)
# 判断执行权限
os.access(, os.x_ok)
# 判断读、写、执行权限
os.access(, os.r_ok | os.w_ok | os.x_ok)
但是如果要判断任意一个指定的用户对某个文件是否有读、写、执行权限,python中是没有默认实现的,此时我们可以通过下面的代码断来判断
import os
import pwd
import stat
def is_readable(cls, path, user):
user_info = pwd.getpwnam(user)
uid = user_info.pw_uid
gid = user_info.pw_gid
s = os.stat(path)
mode = s[stat.st_mode]
return (
((s[stat.st_uid] == uid) and (mode & stat.s_irusr > 0)) or
((s[stat.st_gid] == gid) and (mode & stat.s_irgrp > 0)) or
(mode & stat.s_iroth > 0)
)
def is_writable(cls, path, user):
user_info = pwd.getpwnam(user)
uid = user_info.pw_uid
gid = user_info.pw_gid
s = os.stat(path)
mode = s[stat.st_mode]
return (
((s[stat.st_uid] == uid) and (mode & stat.s_iwusr > 0)) or
((s[stat.st_gid] == gid) and (mode & stat.s_iwgrp > 0)) or
(mode & stat.s_iwoth > 0)
)
def is_executable(cls, path, user):
user_info = pwd.getpwnam(user)
uid = user_info.pw_uid
gid = user_info.pw_gid
s = os.stat(path)
mode = s[stat.st_mode]
return (
((s[stat.st_uid] == uid) and (mode & stat.s_ixusr > 0)) or
((s[stat.st_gid] == gid) and (mode & stat.s_ixgrp > 0)) or
(mode & stat.s_ixoth > 0)
)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。