Monday, May 3, 2010

High Speed Recursive Linux Permission Changer

I wrote this a while back to help aid my needs, I am posting it in case you may find it helpful.

It is fairly easy, you run it in the directory you want to recursively change permissions on.

For example:
perl perms.pl 750 640 zefie zefie
Would set all files under my home directory to 640 (rw/r/-), and all directories to 750 (rwx/rx/-), and make the owner and group "zefie".

#!/usr/bin/perl

# High speed recursive permission changer

$pwd = `pwd`;
$pwd = s/ /\\ /g;

$dmode = @ARGV[0];
$fmode = @ARGV[1];
$user = @ARGV[2];
$group = @ARGV[3];
$verbose = @ARGV[4];

if (!$user || !$group || !$fmode || !$dmode) {
print "Usage: perms.pl dirmode filemode user group [-v]\n";
exit();
}

$files = `find $pwd`;
@files = split("\n",$files);

$i = 0;
$j = 0;
($login,$pass,$uid,$gid) = getpwnam($user);
$gid   = getgrnam($group);

if (!$uid) {
print "User \"".$user."\" does not exist!\n";
exit();
}
if (!$gid) {
print "Group \"".$group."\" does not exist!\n";
exit();
}

foreach $file (@files) {
if (-d $file) {
if ($verbose) {
print "Setting permissions (".$dmode.", ".$uid.":".$gid.") on $file...\n";
}
chmod oct($dmode), $file;
chown $uid, $gid, $file;
}
else {
if ($verbose) {
print "Setting permissions (".$fmode.", ".$gid.":".$uid.") on $file...\n";
}
chmod oct($fmode), $file;
chown $uid, $gid, $file;
}
if (!$verbose) {
$i++;
print "Set permissions on ".$i." objects...";
print "\r";
}
}

if (!$verbose) {
print "\n";
}

No comments:

Post a Comment