openldap scripts and other ldap commands

SCRIPT which will loop through all defined password policies will find users who’s password is about/expired and send mail to them.

#!/usr/bin/perl -w

use strict;
use warnings;
use Net::LDAP;
use Carp;
use DateTime;
use Mail::Sender;

my $ldapserver    = 'ldap://192.100.100.10';
my $basedn        = 'dc=example1,dc=com';
my $defaultpolicy = "cn=default,ou=policies,$basedn";
my ($entry,$warnage);
my %policy;

my $ldap = Net::LDAP->new($ldapserver);
my $mesg;
my $msg1;

#We can do anonymous bind here for now ...
$mesg = $ldap->bind;
$mesg->code && croak $mesg->error;

#2)Find all password policies
$mesg = $ldap->search(    base => $basedn,
        filter => '(objectclass=pwdPolicy)',
        attrs => ['cn','pwdMaxAge','pwdExpireWarning'],
    );
$mesg->code && warn $mesg->error;
foreach $entry ($mesg->entries) {
    print {*STDERR} "Found password policy " . $entry->dn . " with max age " . $entry->get_value('pwdMaxAge') . "\n";
    $warnage = $entry->get_value('pwdMaxAge') - $entry->get_value('pwdExpireWarning');
    my $policyname = $entry->get_value('cn');
    my $policydn = $entry->dn;
    if ($warnage gt 0) {
        #$policy{$entry->dn} = $warnage;
    } else {
        #print "Policy $policydn has no warning time set, or no expiry\n";
        next;
    }
    my $expireage    = $entry->get_value('pwdMaxAge');
    my $warnage      = $entry->get_value('pwdMaxAge') - $entry->get_value('pwdExpireWarning');
    my $filterwarn   = gen_filter($warnage);
    my $filterexpire = gen_filter($expireage);
    my $filter ;
    if ( $entry->dn eq $defaultpolicy ) {  
        $filter = "(&(!(pwdPolicySubEntry=*))(pwdChangedTime<=$filterwarn)(objectclass=Person))"
    } else {
        $filter = "(&(pwdPolicySubEntry=$policydn)(pwdChangedTime<=$filterwarn)(pwdChangedTime>=$filterexpire))"
}
    ###print $filter."\n";
    print "Searching for users about to expire for policy \"$policyname\"\n";

    $mesg = $ldap->search(    base => $basedn,
        filter => $filter,
        attrs => ['cn', 'uid', 'mail', 'pwdChangedTime'],
    );
    $mesg->code && warn $mesg->error;
    my @entries = $mesg->entries;
    foreach $entry (@entries) {
        my $changedtime = $entry->get_value('pwdChangedTime');
        my $willexpire=$filterexpire;
        if ($changedtime =~ m/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\w+)$/) {
            $willexpire=DateTime->new(year=>$1,month=>$2,day=>$3,hour=>$4,minute=>$5,second=>$6,time_zone=>$7);
            $willexpire->add(seconds=>$expireage);
        }
        print "User " . $entry->get_value('uid') . "(" . $entry->get_value('cn') . ")". 
                            " with email " . $entry->get_value('mail') . " has an expired password\n";
        notify_user($entry->get_value('uid'),$entry->get_value('cn'),$entry->get_value('mail')||"",$policyname,$willexpire);

    }
}

$ldap->unbind if (defined $ldap);

sub gen_filter {
    my ($warningtime) = @_;
    my $dt = DateTime->now;
    $dt->subtract(seconds => $warningtime);
    my $filtertime = $dt->strftime('%Y%m%d%H%M%SZ');
    return $filtertime;
}
sub notify_user {
    my ($username,$fullname,$email,$policyname,$expiretime) = @_;
    #$expiretime =~ s/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/$1-$2-$3 $4h$5:$6 (UTC)/;

     my $dt = DateTime->now;
     my $filtertime = $dt->strftime('%Y%m%d%H%M%SZ');

    $expiretime->set_time_zone('Europe/Prague');
    my $expiretimetext = $expiretime->strftime("%Y-%m-%d %H:%M:%S (%Z)");
    my $expiretimetext1 = $expiretime->strftime("%Y%m%d%H%M%S%Z");

    $dt->set_time_zone('Europe/Prague');
    my $filtertimetext = $dt->strftime("%Y-%m-%d %H:%M:%S (%Z)");
     
    ( $filtertime gt $expiretimetext1 ) ? ($msg1 = "Your password expired on $expiretimetext.\n") :
                                          ($msg1 = "Your password will expire on $expiretimetext.\n");

    if ($ENV{'DEBUG'}) {
        print "Warning user $username ($fullname) at $email according to policy $policyname expiring at $expiretimetext\n";
        return 0;
    } else {
    my $mail = new Mail::Sender {
            debug_level => 0,
        smtp => 'smtp.example1.com',
        from => 'Authentication team <root@example1.com>',
        to => ($email ne "") ? "$fullname <$email>" : "Password admin <root\@example1.com>",
        subject => 'Your password is about to expire',
    } or warn "Creating mail failed";

    $mail->Open or warn "Opening mail failed";
    $mail->SendLineEnc(
                      "$filtertimetext,\n\n",
                     "Dear $fullname,\n\n",
                      "Your user id is: $email,\n",
                     "$msg1.\n",
    ) or warn "Adding content to mail failed";

    $mail->Close or warn "Sending mail failed";
    }
}

+++++++++++++++++++++++++++++++++++++++++++++++++++++
create homedir at 1st login
+++++++++++++++++++++++++++++++++++++++++++++++++++++

#!/bin/bash
# create home directory for LDAP user account at the first log on user

VERSION=1.5.0
SCRIPTNAME=`basename $0 | sed "s/\.sh//"`

BINDIR=/opt/install/ldap

LOGDIR=/var/log/mkhome
LOGFILE=$LOGDIR/${SCRIPTNAME}.log

USERLOGGED=`whoami`
LDAPHOMEBASE=/home/homeldap
LDAPHOMEDIR=${LDAPHOMEBASE}/${USERLOGGED}

TIMENOW=$(date +"%Y.%m.%d %H:%M:%S")

# RHEL6 does not provide /etc/ldap.conf
[ -f /etc/ldap.conf ] && LDAPCONF_LINUX=/etc/ldap.conf || LDAPCONF_LINUX=/etc/nslcd.conf

PROFILE_LINUX=$BINDIR/profile_linux
BASHRC_LINUX=$BINDIR/bashrc_linux

usage ()
{
   case $1 in
      -v|--version) 
         echo "$SCRIPTNAME, version $VERSION" 
      ;;
      -h|--help|*)
         echo "Script to create home directory at first logon for the LDAP users"
         echo "Usage: $0 [-v] [-h]"
         echo "       $0 Run the script without argument"
         echo
         echo "       -v --version       Display version"
         echo "       -h --help          Display help"
         echo
      ;;
   esac
}     

printmes ()
{
   printf "%-15s!%-20s!%-12s!%-5s\n" "$SCRIPTNAME" "$TIMENOW" "$1" "$2" >> $LOGFILE
}

create_dir ()
{
   echo "$SCRIPTNAME: creating home directory $1..."

   # Creation of the home directory
   mkdir -m 700 -p $1
   if [ $? -ne 0 ]; then
      printmes "$FUNCNAME" "Error: failed to create home directory $1"
      return 22
   fi
                        
   # Creation of the .profile file
   if [ ! -f $2 ]; then
      printmes "$FUNCNAME" "Error: $2 file is missing!"
   else
      cp $2 $1/.profile
   fi

   # Creation of the .bashrc file
   if [ ! -f $3 ]; then
      printmes "$FUNCNAME" "Error: $3 file is missing!"
   else
      cp $3 $1/.bashrc
   fi

   # Creation of the .ssh stuff
   mkdir -m 700 -p $1/.ssh
   touch $1/.ssh/authorized_keys && chmod 600 $1/.ssh/authorized_keys
 
   # Setting of the Unix rights
   if [ -n "$4" ]; then
      chown -R ${USERLOGGED}:$4 $1      
   else
      printmes "$FUNCNAME" \
         "Error: Can't retrieve your LDAP primary group... Please check your LDAP connection or contact your Unix LDAP admin"
      return 23
   fi
}

# MAIN program

[ -n "$1" ] && usage $1

# Exit if the user is a local/shared ID
grep -q "^${USERLOGGED}:" /etc/passwd
[ $? -eq 0 ] && exit 0

# Exit if the home directory of the LDAP user exists
if [ -d $LDAPHOMEDIR ]; then
   cd $LDAPHOMEDIR
   exit 0
fi

if [ ! -f $LOGFILE ]; then
   echo "# Log file generated by the script $0 on $TIMENOW" > $LOGFILE
   chmod 660 $LOGFILE
fi

if [ ! -d $LDAPHOMEBASE ]; then
   echo "The folder $LDAPHOMEBASE doesn't exist!"
   exit 12
fi

# Exit if /etc/ldap.conf doesn't exist
if [ ! -f $LDAPCONF_LINUX ]; then
   echo "Error: The file $LDAPCONF_LINUX is missing!"
   return 30
fi

ldapgrp=`id -gn $USERLOGGED 2>/dev/null`

create_dir "$LDAPHOMEDIR" "$PROFILE_LINUX" "$BASHRC_LINUX" "$ldapgrp"
if [ $? -ne 0 ]; then
   echo "Script $SCRIPTNAME failed!" 
   echo "Have a look on logfile: $LOGFILE"
   exit 40
fi

echo "$TIMENOW Home directory of $USERLOGGED has been created: $LDAPHOMEDIR" >> $LOGFILE
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s