Using Python to grant file permissions for every intermediate directory down the path

40 Views Asked by At

I have the following (unfinished) code to create directories and assigning owners/permissions.

import os
import pwd
from shutil import chown
import util_directories_owner as dir_owner

base_path = "/usr/local/bin/my_app_01"
subdirectory_names = ["bin", "config", "util/bin", "util/logs", "help"]

for sd_name in subdirectory_names:
    subdirectory_path = os.path.join(base_path, sd_name)
    if not os.path.exists(subdirectory_path):
        try:
            os.makedirs(subdirectory_path)
            try :
                pwd.getpwnam(dir_owner.owner)
                pwd.getgrnam(dir_owner.group)
                shutil.chown(subdirectory_path, dir_owner.owner, dir_owner.group)
                os.chmod(subdirectory_path, 0o664)
            except KeyError as exp:
                print(f"Error: Unable to set owner/group to directory {subdirectory_path} :: {str(exp)}")
        except OSError as exp:
            print(f"Error: Unable to create directory {subdirectory_path} :: {str(exp)}")
        

My current problems are:

  • With os.makedirs(), I can create all the needed intermediate directories for the paths, but I am also trying to recursively grant (at least) read permission for the user for every intermediate directory down the path, and not just the leaf of the path. How can I do that without iterating down the path manually?
  • I do not know how to just add permissions instead of overwriting the permission entirely. In the case that the above code is run more than once, the subdirectories may already exist before the last run. Changes in the permissions may be already applied before the last run. I don't want to overwrite the existing permissions when the code is run again, but I just want to add permissions if missing. Also, I want this to be applied to every intermediate directory that I have created in the process. With bash, I can just manually do something like chmod a+r, if you get what I am trying to do.
  • Down the path, there are some system directories or already existing directories, like /usr/local/bin, which I do not wish to mess with the existing permission settings. What is the best method to avoid touching the permissions for these directories?
0

There are 0 best solutions below