Advertisement
justin_hanekom

chown-dir-user.py

May 13th, 2019 (edited)
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.13 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from __future__ import (
  5.     absolute_import, division, print_function, unicode_literals
  6. )
  7. from nine import (
  8.     IS_PYTHON2, basestring, chr, class_types, filter, integer_types,
  9.     implements_iterator, implements_to_string, implements_repr,
  10.     input, iterkeys, iteritems, itervalues, long, map,
  11.     native_str, nine, nimport, range, range_list, reraise, str, zip
  12. )
  13.  
  14. argparse = nimport('argparse')
  15. grp = nimport('grp')
  16. os = nimport('os')
  17. pwd = nimport('pwd')
  18. sys = nimport('sys')
  19. time = nimport('time')
  20.  
  21.  
  22. def run():
  23.     """Runs this program.
  24.  
  25.    The program ensures that all files under a directory belong to
  26.    a certain user and group.
  27.    """
  28.     start_time = time.time()
  29.     options = parse_cmd_line()
  30.     chown_dir_user(
  31.         user=options['user'],
  32.         directory=options['directory'],
  33.         verbose=options['verbose'])
  34.     if options['verbose']:
  35.         print('Done, in {} seconds!'.format(time.time() - start_time))
  36.  
  37.  
  38. def parse_cmd_line():
  39.     """Parses the command-line arguments.
  40.  
  41.    Arguments:
  42.        None
  43.  
  44.    Returns:
  45.        A dictionary with each of the supplied command-line arguments.
  46.    """
  47.     parser = argparse.ArgumentParser(
  48.         description=' '.join([
  49.             'Sets the user and group of all files under/within a given',
  50.             'directory to a particular user and group']))
  51.     parser.add_argument(
  52.         'user',
  53.         help=' '.join([
  54.             'specify the name of the user/group for files within this',
  55.             'directory']))
  56.     parser.add_argument(
  57.         'directory',
  58.         help=' '.join([
  59.             'specify the directory to look for files',
  60.             'whose owner/group should to be modified']))
  61.     parser.add_argument(
  62.         '--verbose', '-v',
  63.         action='store_true',
  64.         default=False,
  65.         help='specify this to display verbose output')
  66.     # vars() turns Namespace into a regular dictionary
  67.     options = vars(parser.parse_args())
  68.     options['directory'] = chomp_sep(options['directory']) + os.sep
  69.     return options
  70.  
  71.  
  72. def chomp_sep(dir_name):
  73.     """Removes any trailing directory separator characters from the given
  74.    directory name.
  75.  
  76.    Arguments:
  77.        dir_name: the name that has to have any trailing slashes removed
  78.  
  79.    Returns:
  80.        The directory name with no trailing separator characters
  81.    """
  82.     while dir_name.endswith(os.sep):
  83.         dir_name = dir_name[:-1]
  84.     return dir_name
  85.  
  86.  
  87. def chown_dir_user(**kwargs):
  88.     """Removes unneeded files under directory dir_name.
  89.  
  90.    Arguments:
  91.        kwargs: a dictionary with the following keys:-
  92.            user:       the name of the user/group to assign to files under
  93.                        the given directory
  94.            directory:  the root directory under which to search for
  95.                        unneccessary files to delete
  96.            verbose:    whether to output text describing non-fatal events
  97.  
  98.    Returns:
  99.        None
  100.    """
  101.     user = kwargs.pop('user')
  102.     directory = kwargs.pop('directory')
  103.     verbose= kwargs.pop('verbose')
  104.     if kwargs:
  105.         raise TypeError('Unexpected **kwargs: %r' % kwargs)
  106.     uid = pwd.getpwnam(user).pw_uid
  107.     gid = grp.getgrnam(user).gr_gid
  108.     for tupl in os.walk(directory):
  109.         # (dir, subdirs, filenames)
  110.         dir_name = tupl[0].decode(encoding='utf-8', errors='ignore')
  111.         for fname in tupl[2]:
  112.             dir_fname = os.path.join(
  113.                 dir_name,
  114.                 fname.decode(encoding='utf-8', errors='ignore'))
  115.             if os.path.exists(dir_fname):
  116.                 try:
  117.                     stat = os.stat(dir_fname)
  118.                 except OSError as err:
  119.                     print("Unable to stat '{}' - {}".format(dir_fname, err))
  120.                 if stat.st_uid != uid or stat.st_gid != gid:
  121.                     os.chown(dir_fname, uid, gid)
  122.                     if verbose:
  123.                         print("Changed the owner of '{}' to {}:{}".format(
  124.                             dir_fname,
  125.                             user,
  126.                             user))
  127.  
  128.  
  129. if __name__ == '__main__':
  130.     run()
  131.  
Tags: python
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement