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-06-30 08:20:40
  • Python实现获取照片拍摄日期并重命名的方法

    2023-04-14 03:26:37
  • Python的爬虫包Beautiful Soup中用正则表达式来搜索

    2022-12-29 07:15:34
  • SQL语句优化方法30例(推荐)

    2024-01-14 21:55:35
  • 通俗易懂详解Python基础五种下划线作用

    2024-01-01 06:36:22
  • php bootstrap实现简单登录

    2024-04-10 10:42:07
  • 手把手教你Python yLab的绘制折线图的画法

    2023-03-11 21:21:43
  • SQL2005 自动备份的脚本

    2024-01-23 20:34:27
  • php使用Cookie实现和用户会话的方法

    2023-07-08 15:30:49
  • Python中文分词实现方法(安装pymmseg)

    2023-12-06 02:43:41
  • 解析Python中的eval()、exec()及其相关函数

    2023-12-16 02:51:59
  • Python tornado上传文件的功能

    2022-06-01 19:33:37
  • python清除字符串里非字母字符的方法

    2022-08-27 16:04:02
  • Python实现句子翻译功能

    2023-11-20 20:07:28
  • php封装json通信接口详解及实例

    2023-11-14 21:56:26
  • Python如何获取实时股票信息的方法示例

    2021-10-13 19:45:54
  • PHP生成饼图的示例代码

    2023-05-25 10:24:09
  • MySQL Order By索引优化方法

    2024-01-18 10:34:38
  • HTML5的革新:结构之美

    2011-04-16 10:57:00
  • python实现百万答题自动百度搜索答案

    2021-10-06 03:57:11
  • asp之家 网络编程 m.aspxhome.com