Finding Old User Directories using a simple Perl Scipt


Here's a Perl script that identifies home directories where the user is no longer in Active Directory. In some organizations, the user provisioning process may include creating a home directory for the user. However, removing that directory when the user leaves the company may not be standard practice. Legal requirements might require that the data be saved for a period of time, or the user's manager or coworkers might want to keep the data. Over time, you end up with a mess of old homedirs that are filling up all your disk space.

This script reads the directories of a share (which are presumably user names), and tries to find the users in Active Directory. If the user is not found, the size of the directory is calculated and the directory and the size are written to the output file.

use Win32::OLE;
$searchDir="//myHomedirServer/myHomedirShare";
open OUT,">oldHomedirs.txt";

$¦=1;
if(substr($searchDir,length($searchDir)-1) eq "/"){
 $searchDir=substr($searchDir,0,length($searchDir)-1);
}
$dse=Win32::OLE->GetObject("LDAP://RootDSE");
$root=$dse->Get("RootDomainNamingContext");
$adpath="GC://$root";
$base="<".$adpath.">";
$c = Win32::OLE->new("ADODB.Connection");
$c->{Provider} = "ADsDSOObject";
$c->Open("ADSI Provider");
$comm=Win32::OLE->new("ADODB.Command");
$comm->{ActiveConnection}=$c;
$comm->{Properties}->{'Page Size'}=200;
$rs = Win32::OLE->new("ADODB.RecordSet");
$d=opendir(DIR,$searchDir."/");
@subdirs=map ( $_=$searchDir."/".$_, (grep { !/\./ && !/\.\./ &&  -d "$searchDir/$_"} readdir(DIR)));
foreach $subdir (@subdirs){
 ($sourcedir=$subdir)=~s/\//\\/g;
 @pathparts=split /\\/,$sourcedir;
 $user=$pathparts[$#pathparts];
 $targetDir=$destinationPath."\\".$user;
 $comm->{CommandText}="$base;(&(objectCategory=user)(¦(cn=$user)(samAccountName=$user)));adspath;SubTree";
 $rs=$comm->Execute;
 if($rs->{recordCount} < 1){
  $tsize=0;
  print "$sourcedir\t";
  &processdir($sourcedir);
  $fsize=sprintf("%.2f",$tsize/(1024*1024));
  $gtsize=$gtsize+$fsize;
  print "$fsize\n";
  print OUT "$sourcedir\t$fsize\n";
 }
}
$gtgb=sprintf("%.2f",$gtsize/1024);
print OUT "\t$gtsize\t($gtgb GB)\n";
close OUT;
sub processdir{
 my ($dirname)=@_;
 $d=opendir(DIR,$dirname);
 if($d){
  @files=map ( $_=$dirname."/".$_, (grep { -f "$dirname/$_"} readdir(DIR)));
  foreach $filename (@files){
   ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,$atime,$mtime,$ctime,$blksize,$blocks) = stat($filename);
   ($pfilename=$filename)=~s/\//\\/g;
   $tsize=$tsize+$size;
  } 
  rewinddir(DIR);
  my @subdirs=map ($_=$dirname."/".$_,(grep { !/\./ && !/\.\./ && -d "$dirname/$_" } readdir(DIR)));
  foreach $subdir (@subdirs){ &processdir($subdir); }
  undef $dirname;
 }
}

0 comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...