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


Posted in Python onMarch 11, 2020

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

# -*- 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)

以上这篇python检查目录文件权限并修改目录文件权限的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python实现批量获取指定文件夹下的所有文件的厂商信息
Sep 28 Python
Python multiprocessing.Manager介绍和实例(进程间共享数据)
Nov 21 Python
从局部变量和全局变量开始全面解析Python中变量的作用域
Jun 16 Python
django中forms组件的使用与注意
Jul 08 Python
python函数参数(必须参数、可变参数、关键字参数)
Aug 16 Python
Python Web框架之Django框架cookie和session用法分析
Aug 16 Python
Django框架反向解析操作详解
Nov 28 Python
在django项目中导出数据到excel文件并实现下载的功能
Mar 13 Python
python递归调用中的坑:打印有值, 返回却None
Mar 16 Python
解决keras GAN训练是loss不发生变化,accuracy一直为0.5的问题
Jul 02 Python
Python通过fnmatch模块实现文件名匹配
Sep 30 Python
Django框架请求生命周期实现原理
Nov 13 Python
python 链接sqlserver 写接口实例
Mar 11 #Python
浅谈Python中range与Numpy中arange的比较
Mar 11 #Python
python读取当前目录下的CSV文件数据
Mar 11 #Python
python闭包、深浅拷贝、垃圾回收、with语句知识点汇总
Mar 11 #Python
在Python中用GDAL实现矢量对栅格的切割实例
Mar 11 #Python
将 Ubuntu 16 和 18 上的 python 升级到最新 python3.8 的方法教程
Mar 11 #Python
利用Python裁切tiff图像且读取tiff,shp文件的实例
Mar 10 #Python
You might like
投票管理程序
2006/10/09 PHP
PHP代码优化的53个细节
2014/03/03 PHP
php中memcache 基本操作实例
2015/05/17 PHP
编写Js代码要注意的几条规则
2010/09/10 Javascript
基于JavaScript实现 获取鼠标点击位置坐标的方法
2013/04/12 Javascript
Javascript 读取操作Sql中的Xml字段
2014/10/09 Javascript
nodejs事件的监听与触发的理解分析
2015/02/12 NodeJs
jQuery的remove()方法使用详解
2015/08/11 Javascript
基于jQuery实现复选框是否选中进行答题提示
2015/12/10 Javascript
浅析Bootstrap缩略图组件与警示框组件
2016/04/29 Javascript
javascript简易画板开发
2020/04/12 Javascript
基于Javascript倒计时效果
2016/12/22 Javascript
js实现本地时间同步功能
2017/08/26 Javascript
JavaScript之创意时钟项目(实例讲解)
2017/10/23 Javascript
基于input动态模糊查询的实现方法
2017/12/12 Javascript
基于vuex实现购物车功能
2021/01/10 Vue.js
[01:02:38]DOTA2-DPC中国联赛定级赛 LBZS vs Phoenix BO3第二场 1月10日
2021/03/11 DOTA
python创建和使用字典实例详解
2013/11/01 Python
Python生成随机验证码的两种方法
2015/12/22 Python
Python通过命令开启http.server服务器的方法
2017/11/04 Python
python实现神经网络感知器算法
2017/12/20 Python
python中Django文件上传方法详解
2020/08/05 Python
python实现画图工具
2020/08/27 Python
关于python scrapy中添加cookie踩坑记录
2020/11/17 Python
HTML5表单验证特性(知识点小结)
2020/03/10 HTML / CSS
Expedia意大利旅游网站:酒店、机票和租车预订
2017/10/30 全球购物
Roxy俄罗斯官方网站:冲浪和滑雪板的一切
2020/06/20 全球购物
关键字throw与throws的用法差异
2016/11/22 面试题
英语自荐信常用语句
2013/12/13 职场文书
公司企业表扬信
2014/01/11 职场文书
爱情检讨书大全
2014/01/21 职场文书
夫妻忠诚协议书范本
2014/11/17 职场文书
介绍信的写法
2015/01/31 职场文书
2015年大学生实习评语
2015/03/25 职场文书
汽车4S店前台接待岗位职责
2015/04/03 职场文书
详细聊聊浏览器是如何看闭包的
2021/11/11 Javascript