SoFunction
Updated on 2024-11-13

The python operation to check directory file permissions and modify directory file permissions

I'll cut to the chase, or just look at the code!

# -*- coding: utf-8 -*-
# @author flynetcn
import sys, os, pwd, stat, datetime;
 
LOG_FILE = '/var/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');
	(().strftime('%Y-%m-%d %H:%M:%S.%f')+": "+("WARNING " if level else "NOTICE ")+str);
	();
 
def walktree(top, callback):
	for f in (top):
		pathname = (top, f);
		mode = (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:
		(path);
	else:
		(path);
	
 
def checkNginxWritableDirs(paths):
	uid = ('nginx').pw_uid;
	gid = ('nginx').pw_gid;
	for d in paths:
		dstat = (d);
		if dstat.st_uid != uid:
			try:
				(d, uid, gid);
			except:
				logger(1, "chown(%s, nginx, nginx) failed\n" % (d));
 
def checkOtherReadableDirs(paths, isDir=False):
	for d in paths:
		dstat = (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:
					(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);

Additional knowledge: Getting a user's access to a file or directory in Python

In Python we can usually use the () function to get the current user of a file or directory has some kind of permission, but to get a user of a file or directory has some kind of permission python there is no good way to directly get, so I wrote a function to use the stat and pwd module to achieve this function.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pwd
import stat

def is_readable(path, user):
  user_info = (user)
  uid = user_info.pw_uid
  gid = user_info.pw_gid
  s = (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 = (user)
  uid = user_info.pw_uid
  gid = user_info.pw_gid
  s = (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 = (user)
  uid = user_info.pw_uid
  gid = user_info.pw_gid
  s = (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)
   )

Usage

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)

Above this python check directory file permissions and modify directory file permissions operation is all that I have shared with you, I hope to give you a reference, and I hope that you will support me more.