-
# -*- 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);
阅读(1640) | 评论(0) | 转发(0) |