#!/usr/bin/python2.4 # # Copyright 2006 by Vincent Jong a.k.a. megaspaz # All Rights Reserved. # # Script Name: chmod.py """Chmod all files and subdirs in a directory. This script chmods all dirs to 755 and files to 644. It doesn't handle scripts. Usage: chmod.py --dir= [--help] --dir - Directory to traverse. ~ Path expansion not supported. Required. --help - Print this usage and exit. """ import getopt import os import sys __author__ = "Vincent Jong gmail.com>" def GetOptions(): try: opts, args = getopt.getopt(sys.argv[1:], '', ['dir=', 'help']) basedir = None for (name, value) in opts: if name == '--help': # Print usage and exit. sys.stderr.write(__doc__) return 0, None elif name == '--dir': basedir = value.strip() return 0, basedir else: # Throw usage error. raise KeyError if basedir is None: raise KeyError except(getopt.GetoptError, KeyError): # Print usage and exit. sys.stderr.write(__doc__) return 2, None def ChmodFiles(directory): listing = os.listdir(directory) dirlist = [ os.path.join(directory, filename) for filename in listing ] # Loop through the listing looking for sub directories. for somefile in dirlist: # Check if somefile is a symlink. If it is continue. Do not follow. if os.path.islink(somefile): continue if os.path.isdir(somefile): # chmod the directory os.chmod(somefile, 0755) # Traverse this directory ChmodFiles(somefile): else: # This is a regular file. os.chmod(somefile, 0644) def main(): retval, startdir = GetOptions() if retval: # getopt error occurred. return retval else: if startdir is None: # User entered -h for option return retval # Check and see if the directory exists. if not os.path.exists(startdir): sys.stderr.write('Directory does not exist. Aborting.\n') return 1 try: GetFileCount(startdir) return 0 except(IOError, OSError, MemoryError), err: sys.stderr.write('%s\n' % str(err)) return err.errno if '__main__' == __name__: sys.exit(main())