Script - Mount volume based on Active Directory Group Membership

geoffreykobrien
Contributor

I created this for a project recently and thought i'd share it. It will prompt you for your Active Directory login and password, then use that to query your ldap account, and see what groups your a member of. It then uses logic to parse through those group names and run an action upon it, in this case, mounting network drives. You'll want to change all the variables at the top and swap out the and GROUPNAME, SERVERNAME variables in the if statements to mount your drives as well. This may not be suitable for your environment, but feel free to use snippets of the code for your own scripts.

#!/bin/bash
#
# Geoffrey O'Brien
# Network Mount Script
#
# Change the variables below
LDAPURI=ldap.company.com
SEARCHBASE="dc=domain,dc=com"
BINDUSER='domainuser'
BINDPASS='password'
HOSTNAME=hostname | awk -F"." '{print $1}'
CONSOLEUSER=last | grep -m1 console | awk '{print $1}'
USER=""
PASSWORD=""
DOMAIN="DOMAIN"
MOUNTEDVOLUMES='/bin/ls /Volumes'

USER=$(/usr/bin/osascript << EOT
set the_user to text returned of (display dialog "Enter your Username " with title "ENTER A TITLE HERE" default answer "" buttons {"Continue…"} default button 1)
return the_user
EOT)
PASSWORD=$(/usr/bin/osascript << EOT
set the_pass to text returned of (display dialog "Enter your Password " with title "ENTER A TILTLE HERE" default answer "" buttons {"Continue…"} default button 1 with hidden answer)
return the_pass
EOT)

ldapsearch -D "$BINDUSER" -w "$BINDPASS" -h $LDAPURI -b "$SEARCHBASE" -p 3268 -LLL -s sub "(sAMAccountname=$USER)" memberOf | grep memberOf | while read line
do GROUP=echo $line | awk -F: '{printf $2}'| sed -E 's/.CN=([^,]),.*/1/'

if [ "$GROUP" == "GROUPNAME" ]; then VOL="VOLUME" if [ -d /Volumes/$VOL ]; then umount /Volumes/$VOL fi osascript -e 'mount volume "smb://'$DOMAIN';'$USER':'$PASSWORD'@SERVERNAME/'$VOL'"' elif [ "$GROUP" == "GROUPNAME" ]; then VOL="VOLUME" if [ -d /Volumes/$VOL ]; then umount /Volumes/$VOL fi osascript -e 'mount volume "smb://'$DOMAIN';'$USER':'$PASSWORD'@SERVERNAME/'$VOL'"' VOL="VOLUME" if [ -d /Volumes/$VOL ]; then umount /Volumes/$VOL fi osascript -e 'mount volume "smb://'$DOMAIN';'$USER':'$PASSWORD'@SERVERNAME/'$VOL'"' fi
done
open /Volumes

0 REPLIES 0