I thought I’d share a quick script I’ve written to set the permissions for a directory tree. Of course it’s easy to do in a single command if you want the same permissions for directories and files, but that’s almost never the case. In home directories, I need the permissions for files to be 0600 (so the owner only has permission to read and write, but not execute). However for directories I want 0700 (same as before, but with the execute bit set) otherwise the owner won’t be able to enter the directory. I could find no quick or easy way to do this.
I initially tried to write this script in BASH, by essentially tying together ‘find’ and ‘chmod’ but it just wasn’t having it. I needed to read the output of find into an array, but it was interpreting spaces in filenames as separators and so was messing things up – nothing I tried could make it only interpret newlines as separators. So I gave up and wrote it in Python – here it is:
#!/usr/bin/python
from os import chmod
from sys import argv
from os.path import walk
from os import access
from os import W_OK
# get the target directory from the command line
targetdir = argv[1]
def setperms(arg, dirname, names):
writable = access(dirname, W_OK)
if not writable:
print “Ignoring directory “+dirname+”; not writable.”
else:
# set the perms of the directory
chmod(dirname, 0700)
# set the perms of files in the directory
for item in names:
# generate the full relative path
item = dirname+”/”+item
# can we write the individual file?
writable = access(item, W_OK)
if not writable:
print “Ignoring file “+item+”; not writable.”
else:
chmod(item, 0600)
# walk the target directory, calling our function as we go
walk(targetdir, setperms, 0)
Download this code
Simply edit the file to set the permissions you’d like setting – the first (0700) is for directories and the second (0600) is for files. Then call it with the starting path as the first (and only) argument, e.g.:
./setperms.py ./home
The first person to give me the 5-line BASH equivalent gets a punch in the face