I thought I would share a useful utility function for 'chowning' recursively in python. 

I found it useful after running a cron job as 'root' which makes changes to a directory owned by, say, 'www-data'. I needed to change the ownership of the directory back to 'www-data'...


import os
import pwd
import grp


def chown_recursive(path, user, group):
    uid = pwd.getpwnam(user)[2]
    gid = grp.getgrnam(group)[2]
    os.chown(path, uid, gid)
    for root, dirs, files in os.walk(path):
        for name in dirs:
            os.chown(os.path.join(root, name), uid, gid)
        for name in files:
            os.chown(os.path.join(root, name), uid, gid)
    
Loading comments...
';