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实现2048小游戏
Mar 30 Python
Python模块搜索路径代码详解
Jan 29 Python
Python基础教程之if判断,while循环,循环嵌套
Apr 25 Python
使用Windows批处理和WMI设置Python的环境变量方法
Aug 14 Python
Python 3.6打包成EXE可执行程序的实现
Oct 18 Python
手把手教你进行Python虚拟环境配置教程
Feb 03 Python
PyTorch的torch.cat用法
Jun 28 Python
Python读写压缩文件的方法
Jul 30 Python
python批量生成条形码的示例
Oct 10 Python
python 基于opencv实现图像增强
Dec 23 Python
Python之Sklearn使用入门教程
Feb 19 Python
python使用XPath解析数据爬取起点小说网数据
Apr 22 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/02/14 PHP
基于MySQL到MongoDB简易对照表的详解
2013/06/03 PHP
php 使用GD库为页面增加水印示例代码
2014/03/24 PHP
浅谈php安全性需要注意的几点事项
2014/07/17 PHP
Javascript面象对象成员、共享成员变量实验
2010/11/19 Javascript
三种动态加载js的jquery实例代码另附去除js方法
2014/04/30 Javascript
js闭包实例汇总
2014/11/09 Javascript
原生js实现移动开发轮播图、相册滑动特效
2015/04/17 Javascript
Bootstrap 手风琴菜单的实现代码
2017/01/20 Javascript
Vue.js表单标签中的单选按钮、复选按钮和下拉列表的取值问题
2017/11/22 Javascript
js实现ajax的用户简单登入功能
2020/06/18 Javascript
Vue-resource安装过程及使用方法解析
2020/07/21 Javascript
[01:02]DOTA2辉夜杯决赛日 CDEC.Y对阵VG赛前花絮
2015/12/27 DOTA
Python深入学习之上下文管理器
2014/08/31 Python
python使用Pycharm创建一个Django项目
2018/03/05 Python
利用python实现汉字转拼音的2种方法
2019/08/12 Python
对YOLOv3模型调用时候的python接口详解
2019/08/26 Python
python中sort和sorted排序的实例方法
2019/08/26 Python
Python Django实现layui风格+django分页功能的例子
2019/08/29 Python
python爬虫之遍历单个域名
2019/11/20 Python
html5+css3气泡组件的实现
2014/11/21 HTML / CSS
The North Face意大利官网:服装、背包和鞋子
2020/06/17 全球购物
通用自荐信范文
2014/03/14 职场文书
外语专业毕业生自荐信
2014/04/14 职场文书
岗位明星事迹材料
2014/05/18 职场文书
酒店管理求职信
2014/06/09 职场文书
2015年父亲节活动总结
2015/02/12 职场文书
部门经理迟到检讨书
2015/02/16 职场文书
大学生个人简历自我评价
2015/03/11 职场文书
公司团队口号霸气押韵
2015/12/24 职场文书
家访教师心得体会
2016/01/23 职场文书
2016年机关单位节能宣传周活动总结
2016/04/05 职场文书
解决sql server 数据库,sa用户被锁定的问题
2021/06/11 SQL Server
详解nginx安装过程并代理下载服务器文件
2022/02/12 Servers
MySQL读取JSON转换的方式
2022/03/18 MySQL
MySQL 条件查询的常用操作
2022/04/28 MySQL