Bootstrap FreeKB - Python (Scripting) - Change file or directory permissions using os.chmod
Python (Scripting) - Change file or directory permissions using os.chmod

Updated:   |  Python (Scripting) articles

os.chmod can be used to update the permissions of a file or directory. Here is the minimal boilterplate code without error handling. It's important to use 0o for the leading zero due to how this handles octets.

#!/usr/bin/python3
import os
os.chmod(f"/path/to/file", 0o775)

 

Here is a more practical example, with try/except/else error handling.

#!/usr/bin/python3
import os

try:
  os.chmod(f"/path/to/file", 0o775)
except Exception as exception:
  print(f"Got the following exception when attempting to update /path/to/file to mode -rwxrwxr-x (0775) - {exception}")
else:
  print(f"Successfully updated /path/to/file to mode -rwxrwxr-x (0775)")

 

stat can be used for more fine grained control of the permission, such as when you want to add SGID or SUID or Sticky Bit.

#!/usr/bin/python3
import os

file_or_directory = "/path/to/file/or/directory"

try:
  os.chmod(file_or_directory,
           stat.S_IRUSR| # user read
           stat.S_IWUSR| # user write
           stat.S_IXUSR| # user execute
           stat.S_IRGRP| # group read
           stat.S_IWGRP| # group write
           stat.S_IXGRP| # group execute
           stat.S_IROTH| # other read
           stat.S_IXOTH| # other execute
           stat.S_ISGID) # sgid
except Exception as exception:
  print(f"Got the following exception when attempting to update {file_or_directory} to mode -rwxrwsr-x (2775) - {exception}")
else:
  print(f"Successfully updated {file_or_directory} to mode -rwxrwxr-x (2775)")



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter e37707 in the box below so that we can be sure you are a human.