1. 程式人生 > >Python判斷某個使用者對某個檔案的許可權

Python判斷某個使用者對某個檔案的許可權


在Python我們要判斷一個檔案對當前使用者有沒有讀、寫、執行許可權,我們通常可以使用os.access函式來實現,比如:

# 判斷讀許可權
os.access(<my file>, os.R_OK)
# 判斷寫許可權
os.access(<my file>, os.W_OK)
# 判斷執行許可權
os.access(<my file>, os.X_OK)
# 判斷讀、寫、執行許可權
os.access(<my file>, os.R_OK | os.W_OK | os.X_OK)
1
2
3
4
5
6
7
8
但是如果要判斷任意一個指定的使用者對某個檔案是否有讀、寫、執行許可權,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)
)