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 translator使用实例
Sep 06 Python
Python类属性与实例属性用法分析
May 09 Python
python简单实现计算过期时间的方法
Jun 09 Python
在Python的Flask中使用WTForms表单框架的基础教程
Jun 07 Python
python 根据正则表达式提取指定的内容实例详解
Dec 04 Python
Python数据可视化正态分布简单分析及实现代码
Dec 04 Python
Python找出最小的K个数实例代码
Jan 04 Python
Flask模板引擎Jinja2使用实例
Apr 23 Python
Django中的AutoField字段使用
May 18 Python
python获取linux系统信息的三种方法
Oct 14 Python
手残删除python之后的补救方法
Jun 26 Python
Python OpenCV超详细讲解调整大小与图像操作的实现
Apr 02 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
PHP静态新闻列表自动生成代码
2007/06/14 PHP
PHP实现防盗链的方法分析
2017/07/25 PHP
CI框架简单分页类用法示例
2020/06/06 PHP
PHP超全局变量实现原理及代码解析
2020/09/01 PHP
深入聊聊Array的sort方法的使用技巧.详细点评protype.js中的sortBy方法
2007/04/12 Javascript
JavaScript 异步方法队列链实现代码分析
2010/06/05 Javascript
JS基础之undefined与null的区别分析
2011/08/08 Javascript
JS父页面与子页面相互传值方法
2014/03/05 Javascript
jquery判断单选按钮radio是否选中的方法
2015/05/05 Javascript
JS拖拽插件实现步骤
2015/08/03 Javascript
window.onerror()的用法与实例分析
2016/01/27 Javascript
jQuery 的 ready()的纯js替代方法
2016/11/20 Javascript
js return返回多个值,通过对象的属性访问方法
2017/02/21 Javascript
微信小程序 es6-promise.js封装请求与处理异步进程
2017/06/12 Javascript
vue引入swiper插件的使用实例
2017/07/19 Javascript
微信小程序富文本渲染引擎的详解
2017/09/30 Javascript
JavaScript动态加载重复绑定问题
2018/04/01 Javascript
解决使用layui的时候form表单中的select等不能渲染的问题
2019/09/18 Javascript
JavaScript(js)处理的HTML事件、键盘事件、鼠标事件简单示例
2019/11/19 Javascript
python简单获取本机计算机名和IP地址的方法
2015/06/03 Python
Python开发如何在ubuntu 15.10 上配置vim
2016/01/25 Python
python3获取当前文件的上一级目录实例
2018/04/26 Python
Python 十六进制整数与ASCii编码字符串相互转换方法
2018/07/09 Python
基于keras输出中间层结果的2种实现方式
2020/01/24 Python
Python流程控制常用工具详解
2020/02/24 Python
Win10下用Anaconda安装TensorFlow(图文教程)
2020/06/18 Python
Python 字典一个键对应多个值的方法
2020/09/29 Python
AmazeUI 网格的实现示例
2020/08/13 HTML / CSS
行政总监岗位职责
2013/12/05 职场文书
商场客服专员岗位职责
2014/06/13 职场文书
党员干部群众路线个人整改措施
2014/09/18 职场文书
党的群众路线专项整治方案
2014/11/03 职场文书
2014年党风廉政建设工作总结
2014/11/19 职场文书
置业顾问岗位职责
2015/02/09 职场文书
就业导师推荐信范文
2015/03/27 职场文书
行政前台岗位职责
2015/04/16 职场文书