use dscl to verify if a Mac is still bound to Active Directory

In my company we use an automated system to generate computer names and image Macs with those names. This type of solution makes it extremely easy to image and deploy new equipment for growth units, for new hires, for training labs, etc.

The problem with such an automated solution comes in, however, when one needs to REimage a Mac in order to repurpose it, or repair a broken hard drive, possibly a logic board, etc. As you know, dsconfigad is the command to use for binding from the command line, and you must use the ‘-force’ flag to make it run unattended by automatically assuming a ‘yes’ answer to every question. When binding a brand new Mac this isn’t a problem, but when reimaging a mac and binding it a second time, this can cause a problem.

The built-in Active Directory plugin on a Mac will check for existing computer accounts for that particular Mac during the bind process. It takes the MAC address and Mac name into account when searching for existing accounts. If it does not find a match to either of these, it will create the new record in AD. However if it does find a match to at least one of them, it asks “Would you like to use the existing account?” Since the -force option is autoanswering yes, The AD plugin will join the active directory using the existing computer account. Now this is fine if you are binding with the same name the Mac had previously. In our organization, a new name is generated every time a Mac is imaged or reimaged, so this is NOT fine, and we can frequently end up with a Mac that has one name on the network, but a completely different name in active directory, all because it had the same MAC address.

In order to help avoid this, I’ve added this bit of logic into my imaging scripts:

ComputerName=`diskutil list | grep disk0 | grep "2:" | awk '{print $3}'`
## Find if the computer is already in Active Directory. If it is, exit. We need to remove it from AD
IsInAD=$(dscl /Active\ Directory/All\ Domains/ -read /Computers/$ComputerName$ | grep UniqueID)

First we get the computer name. Since we use netboot when imaging a Mac at my company, we cannot use scutil – that assumes the current boot drive. So we rely on the fact that the Mac name is the same as the boot drive. Then we use ‘dscl’ to walk the directory and search for that computer name and finally grep out UniqueID. If the variable ‘IsInAD’ is blank, the computer is NOT in AD. If there is a value in ‘IsInAD’, then we know that Mac is still has a record in AD. Currently we do not automatically delete the record, we just exit the script.

About this entry