babymaker  e95a6a9342d4604277fe7cc6149b6b5b24447d89
lock_files.py
Go to the documentation of this file.
1 #! /usr/bin/env python
2 
3 import argparse
4 import glob
5 import errno
6 import os
7 import pwd
8 import grp
9 
10 def fullPath(path):
11  return os.path.realpath(os.path.abspath(os.path.expanduser(path)))
12 
13 def lock(file_dir, unlock_dirs):
14  ruid = 0
15  rgid = 0
16  try: ruid = pwd.getpwnam("root").pw_uid
17  except KeyError: pass
18  try: rgid = grp.getgrnam("root").gr_gid
19  except KeyError: pass
20 
21  try:
22  with open(file_dir) as f:
23  try: os.fchmod(f.fileno(), 0444)
24  except OSError as e:
25  if e.errno != errno.EPERM: raise
26  try: os.fchown(f.fileno(), ruid, -1)
27  except OSError as e:
28  if e.errno != errno.EPERM: raise
29  try: os.fchown(f.fileno(), -1, rgid)
30  except OSError as e:
31  if e.errno != errno.EPERM: raise
32  except IOError as e:
33  if e.errno != errno.EISDIR: raise
34  else:
35  try: os.chmod(file_dir, 0777 if unlock_dirs else 0555)
36  except OSError as e:
37  if e.errno != errno.EPERM: raise
38  try: os.chown(file_dir, ruid, -1)
39  except OSError as e:
40  if e.errno != errno.EPERM: raise
41  try: os.chown(file_dir, -1, rgid)
42  except OSError as e:
43  if e.errno != errno.EPERM: raise
44 
45 def lockFiles(file_dirs, unlock_dirs):
46  file_dirs = [ fullPath(f) for sublist in file_dirs for f in glob.glob(sublist) ]
47 
48  for file_dir in file_dirs:
49  for root, dirs, files in os.walk(file_dir):
50  for f in files:
51  lock(os.path.join(root,f), unlock_dirs)
52  lock(root, unlock_dirs)
53 
54 if __name__ == "__main__":
55  parser = argparse.ArgumentParser(description="Sets directories to R+W and files to R permissions. Also tries to make the owner root.",
56  formatter_class = argparse.ArgumentDefaultsHelpFormatter)
57  parser.add_argument("file_or_dir", default = ["."], nargs = "*",
58  help="List of files and/or directories to lock.")
59  parser.add_argument("-u","--unlock_dirs", action="store_true", help="Leave directories unlocked for addition/removal of files")
60  args = parser.parse_args()
61 
62  lockFiles(args.file_or_dir, args.unlock_dirs)
def lock(file_dir, unlock_dirs)
Definition: lock_files.py:13
def lockFiles(file_dirs, unlock_dirs)
Definition: lock_files.py:45
def fullPath(path)
Definition: lock_files.py:10