Last active
May 30, 2019 21:52
-
-
Save ibarland/1a7c6072a8c81505631fa48eabac2555 to your computer and use it in GitHub Desktop.
chownR_If: For every file+dir rooted at `root`, if the owner of that file/dir is `targetUid`, then change the owner to `replacementUid`.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python3 | |
import os | |
def chownIf(path, targetUid, replacementUid ): | |
"""If the owner of `path` is `targetUid`, then change the owner to `replacementUid`. | |
(UID's are numeric, not string.) | |
BUG -- this doesn't work: Also, if a link is owned by root(0), change it to `replacementUid` as well. | |
""" | |
ownerUid = os.stat(path).st_uid | |
if ownerUid == targetUid: | |
print( "Changing from owner " + str(ownerUid) + " to " + str(targetUid) + " for " + path | |
os.chown(path, replacementUid, -1, follow_symlinks=False) | |
if os.path.islink(path) and ownerUid == 0: | |
# bug: this doesn't seem to work (the unix `chown` doesn't change link owners ... but it rarely matters?) | |
os.chown(path, replacementUid, -1, follow_symlinks=False) | |
def chownRIf( root, targetUid, replacementUid ): | |
"""For every file rooted at `root`, including `.`, `chownIf` it (see `chownIf`).""" | |
chownIf(root,targetUid,replacementUid) # `.` handled specially (!) | |
for (subdir,dirs,files) in os.walk(root): | |
for name in dirs+files: | |
chownIf(os.path.join(subdir,name), targetUid, replacementUid) | |
chownRIf( "/Users/ibarland/Tmp/Tmp2", 501, 502 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment