#  ADSIDisplaySessions.pl
#  Example 9.9:
#  ----------------------------------------
#  From "Win32 Perl Scripting: Administrators Handbook" by Dave Roth
#  Published by New Riders Publishing.
#  ISBN # 1-57870-215-1
#
#  This script displays the what accounts are enabled or disabled.
#
print "From the book 'Win32 Perl Scripting: The Administrator's Handbook' by Dave Roth\n\n";


use Getopt::Long;
use Win32;
use Win32::OLE qw( in );

Configure( \%Config );
foreach my $MachineName ( @ARGV )
{
  my $ADsPath;
  my $Machine;
  print "\n$MachineName:\n";
  $MachineName =~ s#\\#/#g;
  $ADsPath = "WinNT://$MachineName,computer";
  next unless( $Machine = Win32::OLE->GetObject( $ADsPath ) );
  
  if( my $FileService = $Machine->GetObject( "FileService", 
                                             "LanmanServer" ) )
  {
    my $Sessions = $FileService->{Sessions};
    local $Session;

    $~ = SESSION_HEADER_FORMAT;
    write;
    $~ = SESSION_FORMAT;
    foreach $Session ( in( $Sessions ) )
    {
      local %Time = ( 
        connect => FormatTime( $Session->{ConnectTime} ), 
        idle    => FormatTime( $Session->{IdleTime} )
      );
      $Sessions->Remove( $Session->{Name} ) if( $Config{disconnect} );
      write;
    }
  }
}

sub Configure
{
  my( $Config ) = @_;
  my $Result;
  Getopt::Long::Configure( "prefix_pattern=(-|\/)" );
  $Result = GetOptions( $Config, "disconnect|d" );
  return();              
}

sub FormatTime
{
    my( $Seconds ) = @_;
    my( $Day, $Hour, $Min, $Sec, $Delta );
    $Day = int( $Seconds / ( 3600 * 24 ) );
    $Delta = $Seconds % ( 3600 * 24 );
    $Hour = int( $Delta / 3600 );
    $Delta = $Delta % 3600;
    $Min = int( $Delta / 60 );
    $Sec = int( $Delta % 60 );
    return( sprintf( "%02d:%02d:%02d:%02d",
                     $Day, $Hour, $Min, $Sec ) );
}

format SESSION_HEADER_FORMAT =
User           Computer        Connection Time Idle Time
-------------- --------------- --------------- -----------
.
format SESSION_FORMAT =
@<<<<<<<<<<<<< @<<<<<<<<<<<<<< @<<<<<<<<<<<<<< @<<<<<<<<<<
$Session->{User}, $Session->{Computer}, $Time{connect}, $Time{idle}
.
