Monday, March 31, 2008

Dump Unix File Mode and Ownership

I found several situations where I needed to recursively record file ownerships and permissions for the sake of documentation or to restore them later. I didn’t bother making something to do it until I had a project that required it.



This might not be the smartest way to go about this. I recognize that this functionality exists in rsync but you might not want to copy the files or you might want to recover this information later rather than on a remote system.



Dump



The following find command will recurse on /path and dump the uid, gid, mode, and path for each file into /path/to/dump. Be aware that if your dump file is within /path it is likely to appear in the list.




find /path -exec stat --format '%u %g %a %n' {} \; >> /path/to/dump


Restore



The following short perl script will read one or more dump files from standard input or as command line arguments and apply set the owner, group, and mode for each file therein. For this work it must be run as root or via sudo.




#!/usr/bin/perl
# Read a mode/owner dump from standard input or as command line arguments

use strict;

while (my $input = <>) {
chomp $input;
my ($uid,$gid,$mode,$path) = split(/\s+/,$input);
print "$path: $uid:$gid $mode\n";
chmod oct($mode), $path;
chown $uid, $gid, $path;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.