• Python 查看文件的读写权限方法


     
    # -*- coding: utf-8 -*-
    # @author flynetcn
    import sys, os, pwd, stat, datetime;
    LOG_FILE = '/var/log/checkDirPermission.log';
    nginxWritableDirs = [
    '/var/log/nginx',
    '/usr/local/www/var',
    ];
    otherReadableDirs = [
    '/var/log/nginx',
    '/usr/local/www/var/log',
    ];
    dirs = [];
    files = [];
    def logger(level, str):
        logFd = open(LOG_FILE, 'a');
        logFd.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')+": "+("WARNING " if level else "NOTICE ")+str);
        logFd.close();
    def walktree(top, callback):
        for f in os.listdir(top):
            pathname = os.path.join(top, f);
            mode = os.stat(pathname).st_mode;
            if stat.S_ISDIR(mode):
                callback(pathname, True);
                walktree(pathname, callback);
            elif stat.S_ISREG(mode):
                callback(pathname, False);
            else:
                logger(1, "walktree skipping %s " % (pathname));
    def collectPath(path, isDir=False):
        if isDir:
            dirs.append(path);
        else:
            files.append(path);
         
    def checkNginxWritableDirs(paths):
        uid = pwd.getpwnam('nginx').pw_uid;
        gid = pwd.getpwnam('nginx').pw_gid;
        for d in paths:
            dstat = os.stat(d);
            if dstat.st_uid != uid:
                try:
                    os.chown(d, uid, gid);
                except:
                    logger(1, "chown(%s, nginx, nginx) failed " % (d));
    def checkOtherReadableDirs(paths, isDir=False):
        for d in paths:
            dstat = os.stat(d);
            if isDir:
                checkMode = 5;
                willBeMode = dstat.st_mode | stat.S_IROTH | stat.S_IXOTH;
            else:
                checkMode = 4;
                willBeMode = dstat.st_mode | stat.S_IROTH;
            if int(oct(dstat.st_mode)[-1:]) & checkMode != checkMode:
                try:
                        os.chmod(d, willBeMode);
                except:
                    logger(1, "chmod(%s, %d) failed " % (d, oct(willBeMode)));
    if __name__ == "__main__":
        for d in nginxWritableDirs:
            walktree(d, collectPath)
        dirs = dirs + files;
        checkNginxWritableDirs(dirs);
        dirs = [];
        files = [];
        for d in otherReadableDirs:
            walktree(d, collectPath)
        checkOtherReadableDirs(dirs, True);
        checkOtherReadableDirs(files, False);
     
     

    os.chmod(path,mode) 这个方法应该很简单,只需要2个参数,一个是路径,一个是说明路径的模式,下面列出了这个用法中可以使用的一些常用的模式:

    stat.S_ISUID: Set user ID on execution. 不常用

    stat.S_ISGID: Set group ID on execution. 不常用

    stat.S_ENFMT: Record locking enforced. 不常用

    stat.S_ISVTX: Save text image after execution. 在执行之后保存文字和图片

    stat.S_IREAD: Read by owner. 对于拥有者读的权限

    stat.S_IWRITE: Write by owner. 对于拥有者写的权限

    stat.S_IEXEC: Execute by owner. 对于拥有者执行的权限

    stat.S_IRWXU: Read, write, and execute by owner. 对于拥有者读写执行的权限

    stat.S_IRUSR: Read by owner. 对于拥有者读的权限

    stat.S_IWUSR: Write by owner. 对于拥有者写的权限

    stat.S_IXUSR: Execute by owner. 对于拥有者执行的权限

    stat.S_IRWXG: Read, write, and execute by group. 对于同组的人读写执行的权限

    stat.S_IRGRP: Read by group. 对于同组读的权限

    stat.S_IWGRP: Write by group. 对于同组写的权限

    stat.S_IXGRP: Execute by group. 对于同组执行的权限

    stat.S_IRWXO: Read, write, and execute by others. 对于其他组读写执行的权限

    stat.S_IROTH: Read by others. 对于其他组读的权限

    stat.S_IWOTH: Write by others. 对于其他组写的权限

    stat.S_IXOTH: Execute by others. 对于其他组执行的权限

    1
    2
    3
    4
    5
    6
    7
    8
    >>> os.stat('test')
    posix.stat_result(st_mode=33204, st_ino=93328670, st_dev=18L, st_nlink=1, st_uid=30448, st_gid=1000, st_size=0, st_atime=1445932321, st_mtime=1445932321, st_ctime=1445932321)
    >>> os.stat('test').st_mode
    33204
    >>> oct(os.stat('test').st_mode)
    '0100664'
    >>> oct(os.stat('test').st_mode)[-3:]
    '664'

    在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)
    )

  • 相关阅读:
    (转)用JMX监测JVM的运行参数
    MySql
    ORACLE小工具:存储过程清空所有表或使所有触发器失效
    简单易懂,原码,补码,反码
    centos7如何关闭防火墙
    中兴大事件
    苹果降频门:旧款iPhone哪些功能受到影响
    苹果降频门
    华为P10闪存门
    N32903系列的基础知识(1)
  • 原文地址:https://www.cnblogs.com/phoenix-mountain/p/12954549.html
Copyright © 2020-2023  润新知