Skip to content

Instantly share code, notes, and snippets.

@antonlindstrom
Created May 6, 2009 09:40
Show Gist options
  • Save antonlindstrom/107454 to your computer and use it in GitHub Desktop.
Save antonlindstrom/107454 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
#
# Anton Lindstrom
#
# Program to print out files for users.
# Controlling directory recursive and sets
# files in array.
#
use warnings;
use POSIX qw/ceil/;
$base_path = "/tmp";
print "Scanning directory $base_path ...\n\n";
pfiles($base_path);
formatprint(@glob_files);
# Recurse path and set all files in array.
sub pfiles {
$path = $_[0];
opendir (DIR, $path) || warn "$path could not be accessed!\n $!\n";
# Adding full path, removing . and .. then reading dir.
# @files contains all files. Local, not to interfere with
# the recurse function.
my @files =
map { $path . '/' . $_ }
grep { !/^\.{1,2}$/ }
readdir (DIR);
closedir (DIR);
# Recurse all folders.
foreach (@files) {
if (-f $_) { push (@glob_files, $_); }
elsif (-d $_) { pfiles($_); }
}
}
# Format and print..
sub formatprint {
@statfiles = @_;
# Open /etc/passwd to get user name and uid.
open(USR, "/etc/passwd") || die "/etc/passwd could not be accessed!\n $!\n";
@users = <USR>;
foreach (@users) {
@usrposts = split(/:/, $_);
# Set user uid as key and username as value.
$user{$usrposts[2]} = $usrposts[0];
}
foreach (@statfiles) {
# Check file..
if (-f $_) {
@check = stat($_);
$uid = $check[4];
$size = $check[7];
$filesize{$_} = $size;
$fileowner{$_} = $uid;
}
}
$userfilesize = 0;
# Print all users with files..
foreach $uidn(keys(%user)) {
# Do not print users below 1000 (root and such), do not print user nobody either..
next if ($uidn < 1000 || $uidn == 65534);
# Format and set values before printout.
foreach $key(sort { $filesize{$b} <=> $filesize{$a}} keys(%filesize) ) {
if ( ($uidn == $fileowner{$key}) ) {
# Put formatted value in an array and count filesize.
push (@formattedval, "\t\t$key\t $filesize{$key} (".ceil(($filesize{$key}/1024)/1024)."MiB)\n");
$userfilesize += $filesize{$key};
}
}
# Skip if users do not have any files.
next if ($userfilesize == 0);
print "User $uidn ($user{$uidn})\n";
$numbers = scalar(@formattedval);
# Print.
print "\tTotal file usage: $userfilesize (".ceil(($userfilesize/1024)/1024)."MiB)\n";
print "\tNumber of files: $numbers\n";
print "\tLargest files:\n";
# Only print out the five largest files.
$i=0;
foreach (@formattedval) {
next if ($i == 5);
$i++;
print $_;
}
# Clear the array
@formattedval = ();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment