ldapsearch and ldapdelete examples

It happens sometimes that you want to run some command but you do not remember the whole syntax. Then you go to the man page to find that it has a ton of switches, you scroll to the bottom hoping to find an example you can re-use but there is none, then you Google it hoping that you won’t have to read the ton of switches. Here is my contribution for those Google searches with two useful ldap commands.

This is a simple script that connects to Active Directory, looks for a computer record and then deletes it.

#!/bin/bash
#Delete the existing (if any) computer record in AD for this computer.

ADUSERNAME="PRETENDCO\privileged"
ADPASSWORD="ThePass"
HOSTNAME=`scutil --get HostName`

if [ "`ldapsearch -h pretendco.com -x -b "cn=computers,dc=pretendco,dc=com" -D "${ADUSERNAME}" -w "${ADPASSWORD}" "cn=${HOSTNAME}" | grep numEntries`" != "" ]; then
	#get the full DN location. AD is not case sensitive, still lowercase it is my choice
	DNLOCATION=`ldapsearch -LLL -h pretendco.com -x -b "cn=computers,dc=pretendco,dc=com" -D "${ADUSERNAME}" -w "${ADPASSWORD}" "cn=${HOSTNAME}" | grep "dn:" | awk '{gsub("dn: ", "");print}' | tr "[:upper:]" "[:lower:]"`
	echo "INFO: Computer's dn was ${DNLOCATION}"
	ldapdelete -h pretendco.com -D "${ADUSERNAME}" -w "${ADPASSWORD}" "${DNLOCATION}" 1>&2
else
	echo "INFO: This computer was not found in AD"
fi

exit 0

Quick explanation of the switches used:

-h –> host to connect to

-x –> simple authentication

-b –> base where to start the search

-D –> username to authenticate as

-w –> password for that user. Seeing this should alarm you

then you put the property that the search must meet to be true

-LLL –> removes the extra comments and mostly useless lines

ldapdelete is to be used with extreme caution! provide the full path of the object to delete.

Posted in IT and stuff Tagged with: , , , ,
0 comments on “ldapsearch and ldapdelete examples
1 Pings/Trackbacks for "ldapsearch and ldapdelete examples"
  1. [...] Alonso has a post outlining one way you could easily delete a machine out of Active Directory using ldapsearch and [...]

Leave a Reply