Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1176452
  • 博文数量: 252
  • 博客积分: 5421
  • 博客等级: 大校
  • 技术积分: 2418
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-17 12:59
文章分类

全部博文(252)

文章存档

2017年(3)

2016年(18)

2015年(31)

2014年(18)

2013年(7)

2012年(8)

2011年(12)

2010年(30)

2009年(32)

2008年(57)

2007年(36)

分类: Python/Ruby

2015-08-17 15:29:47


  1. # -*- coding: utf-8 -*-
  2. # @author flynetcn
  3. import sys, os, pwd, stat, datetime;

  4. LOG_FILE = '/var/log/checkDirPermission.log';

  5. nginxWritableDirs = [
  6. '/var/log/nginx',
  7. '/usr/local/www/var',
  8. ];

  9. otherReadableDirs = [
  10. '/var/log/nginx',
  11. '/usr/local/www/var/log',
  12. ];

  13. dirs = [];
  14. files = [];

  15. def logger(level, str):
  16.     logFd = open(LOG_FILE, 'a');
  17.     logFd.write(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')+": "+("WARNING " if level else "NOTICE ")+str);
  18.     logFd.close();

  19. def walktree(top, callback):
  20.     for f in os.listdir(top):
  21.         pathname = os.path.join(top, f);
  22.         mode = os.stat(pathname).st_mode;
  23.         if stat.S_ISDIR(mode):
  24.             callback(pathname, True);
  25.             walktree(pathname, callback);
  26.         elif stat.S_ISREG(mode):
  27.             callback(pathname, False);
  28.         else:
  29.             logger(1, "walktree skipping %s\n" % (pathname));

  30. def collectPath(path, isDir=False):
  31.     if isDir:
  32.         dirs.append(path);
  33.     else:
  34.         files.append(path);
  35.     

  36. def checkNginxWritableDirs(paths):
  37.     uid = pwd.getpwnam('nginx').pw_uid;
  38.     gid = pwd.getpwnam('nginx').pw_gid;
  39.     for d in paths:
  40.         dstat = os.stat(d);
  41.         if dstat.st_uid != uid:
  42.             try:
  43.                 os.chown(d, uid, gid);
  44.             except:
  45.                 logger(1, "chown(%s, nginx, nginx) failed\n" % (d));

  46. def checkOtherReadableDirs(paths, isDir=False):
  47.     for d in paths:
  48.         dstat = os.stat(d);
  49.         if isDir:
  50.             checkMode = 5;
  51.             willBeMode = dstat.st_mode | stat.S_IROTH | stat.S_IXOTH;
  52.         else:
  53.             checkMode = 4;
  54.             willBeMode = dstat.st_mode | stat.S_IROTH;
  55.         if int(oct(dstat.st_mode)[-1:]) & checkMode != checkMode:
  56.             try:
  57.                     os.chmod(d, willBeMode);
  58.             except:
  59.                 logger(1, "chmod(%s, %d) failed\n" % (d, oct(willBeMode)));

  60. if __name__ == "__main__":
  61.     for d in nginxWritableDirs:
  62.         walktree(d, collectPath)
  63.     dirs = dirs + files;
  64.     checkNginxWritableDirs(dirs);
  65.     dirs = [];
  66.     files = [];
  67.     for d in otherReadableDirs:
  68.         walktree(d, collectPath)
  69.     checkOtherReadableDirs(dirs, True);
  70.     checkOtherReadableDirs(files, False);


阅读(1596) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~