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实现抓取网页生成Excel文件的方法示例
Aug 05 Python
对python list 遍历删除的正确方法详解
Jun 29 Python
python3中函数参数的四种简单用法
Jul 09 Python
python删除字符串中指定字符的方法
Aug 13 Python
Python将json文件写入ES数据库的方法
Apr 10 Python
Python 存储字符串时节省空间的方法
Apr 23 Python
Python实现微信消息防撤回功能的实例代码
Apr 29 Python
python中dict使用方法详解
Jul 17 Python
python3.7添加dlib模块的方法
Jul 01 Python
Python实现自动签到脚本的示例代码
Aug 19 Python
python实现杨辉三角的几种方法代码实例
Mar 02 Python
Python+Tkinter打造签名设计工具
Apr 01 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一次性删除前台checkbox多选内容的方法
2013/09/22 PHP
PHP微信开发之二维码生成类
2015/06/26 PHP
jquery 图片截取工具jquery.imagecropper.js
2010/04/09 Javascript
网页中可关闭的漂浮窗口实现可自行调节
2013/08/20 Javascript
js创建元素(节点)示例
2014/01/02 Javascript
JS利用cookie记忆当前位置的防刷新导航效果
2015/10/15 Javascript
jquery简单倒计时实现方法
2015/12/18 Javascript
酷! 不同风格页面布局幻灯片特效js实现
2021/02/19 Javascript
jquery获取input type=text中的值的各种方式(总结)
2016/12/02 Javascript
详解js树形控件—zTree使用总结
2016/12/28 Javascript
浅谈javascript的闭包
2017/01/23 Javascript
NodeJs使用Mysql模块实现事务处理实例
2017/05/31 NodeJs
Vue集成Iframe页面的方法示例
2017/12/12 Javascript
vue插件开发之使用pdf.js实现手机端在线预览pdf文档的方法
2018/07/12 Javascript
webpack打包多页面的方法
2018/11/30 Javascript
Nodejs在局域网配置https访问的实现方法
2020/10/17 NodeJs
[46:14]VGJ.T vs Liquid 2018国际邀请赛小组赛BO2 第一场 8.19
2018/08/21 DOTA
[01:00:10]完美世界DOTA2联赛PWL S2 FTD vs Inki 第二场 11.21
2020/11/24 DOTA
Python 变量类型及命名规则介绍
2013/06/08 Python
python在命令行下使用google翻译(带语音)
2014/01/16 Python
python 3.6 +pyMysql 操作mysql数据库(实例讲解)
2017/12/20 Python
对Python3使运行暂停的方法详解
2019/02/18 Python
django 消息框架 message使用详解
2019/07/22 Python
Pycharm连接远程服务器并实现远程调试的实现
2019/08/02 Python
解决Mac下使用python的坑
2019/08/13 Python
tensorflow通过模型文件,使用tensorboard查看其模型图Graph方式
2020/01/23 Python
python实现凯撒密码、凯撒加解密算法
2020/06/11 Python
python能否java成为主流语言吗
2020/06/22 Python
AmazeUI 导航条的实现示例
2020/08/14 HTML / CSS
车间副主任岗位职责
2013/12/24 职场文书
结婚喜宴主持词
2014/03/14 职场文书
综艺节目策划方案
2014/06/13 职场文书
机械原理课程设计心得体会
2016/01/15 职场文书
Windows下使用Nginx+Tomcat做负载均衡的完整步骤
2021/03/31 Servers
零基础学java之带参数以及返回值的方法
2022/04/10 Java/Android
阿里云ECS云服务器快照的概念以及如何使用
2022/04/21 Servers