python检查目录文件权限并修改目录文件权限的操作

作者:flynetcn 时间:2022-06-26 04:13:31 

我就废话不多说了,还是直接看代码吧!


# -*- 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\n" % (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\n" % (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\n" % (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);

补充知识:Python中获取某个用户对某个文件或目录的访问权限

在Python中我们通常可以使用os.access()函数来获取当前用户对某个文件或目录是否有某种权限,但是要获取某个用户对某个文件或目录是否有某种权限python中没有很好的方法直接获取,因此我写了个函数使用stat和pwd模块来实现这一功能。


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pwd
import stat

def is_readable(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(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(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)
  )

使用方法


print is_readable('/home', root)
print is_writable('/home', root)
print is_executable('/home', root)

print is_readable('/tmp', admin)
print is_writable('/tmp', admin)
print is_executable('/tmp', admin)

来源:https://blog.csdn.net/flynetcn/article/details/47725741

标签:python,目录,文件权限
0
投稿

猜你喜欢

  • Python获取浏览器窗口句柄过程解析

    2022-05-25 10:37:33
  • Python识别二维码的两种方法详解

    2022-08-20 23:44:12
  • 一个不错的js软键盘代码而且移植方便

    2007-08-14 12:56:00
  • Python中关键字is与==的区别简述

    2022-07-09 10:32:09
  • 三分钟掌握PHP操作数据库

    2023-06-01 01:15:43
  • 如何检测Oracle的ODBC是否连接成功?

    2009-11-24 20:31:00
  • asp防止同时登陆的问题

    2007-10-26 12:19:00
  • Python基于pyecharts实现关联图绘制

    2021-04-08 12:05:45
  • python控制台显示时钟的示例

    2023-10-23 12:04:24
  • 简单了解python的内存管理机制

    2021-10-03 18:13:11
  • 关于使用python反编译apk签名出包的问题

    2022-12-19 19:39:04
  • asp中的on error resume next用法

    2008-03-09 15:22:00
  • MySQL转义字符

    2011-06-19 16:06:04
  • 对python借助百度云API对评论进行观点抽取的方法详解

    2023-12-06 19:42:12
  • Python随机函数库random的使用方法详解

    2021-06-07 16:16:23
  • css+JavaScript实现PDF、ZIP、DOC链接的标注

    2007-05-11 17:03:00
  • django 在原有表格添加或删除字段的实例

    2023-11-25 04:21:08
  • asp access数据库并生成XML文件范例

    2011-03-29 10:49:00
  • python爬虫实例详解

    2021-07-05 01:37:53
  • python 插入日期数据到Oracle实例

    2022-09-29 23:51:59
  • asp之家 网络编程 m.aspxhome.com