Tuesday, April 6, 2010

chown in Python

The built-in chown in Python (in the os module) only uses uid/gid instead of username/groupname. So here's a couple of (simple) versions that can take usernames and groupnames. I can't remember where I borrowed some of this code from, but it was heavily inspired by code samples I found while google searching:


def chown(path,user,group):
uid = pwd.getpwnam(user)[2]
gid = grp.getgrnam(group)[2]
os.chown(path,uid,gid)

def chown_recursive(path,user,group):
if path is None or path in ['/','/root','/usr','/tmp','/bin','/sbin']:
raise Error("path isn't right...")
uid = pwd.getpwnam(user)[2]
gid = grp.getgrnam(group)[2]
os.chown(root, 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)

No comments: