Script to obtain AD canonical name of computer

martingownes
New Contributor

Hi,

I am trying to create a script to populate a extension attribute with the Active Directory canonical name. This is what my attempt (blundering attempt, I have no experience either in bash scripting or JAMF):

!/bin/sh

DomainName=$(dsconfigad -show | awk '/Active Directory Domain/{print $NF}')
CompName=$(dsconfigad -show | grep "Computer Account" | awk '{ print $4 }')

CanonicalName=$(dscl "/Active Directory/${DomainName}/All Domains" read /Computers/${CompName}$ dsAttrTypeNative:CanonicalName | tail -1 | awk -F ':' '{print $3}')

echo "<result>${CanonicalName}</result>"
exit 0

Thanks

1 REPLY 1

ryan_ball
Valued Contributor

@martingownes From looking at my Mac, Canonical name is not listed as an attribute when using dscl. I have modified the script to give you the distinguished name (dn) of the mac. I think the part that was getting you was that you were trying to using the full domain name in your last dscl command and it really needs to be the short domain name (not contoso.com, but CONTOSO). You need to run this as root even during your testing.

#!/bin/bash
# If full domain is contoso.com, you need to capture the CONTOSO only part, but you can get this from the Keychain
DomainName=$(/usr/bin/security dump-keychain -d /Library/Keychains/System.keychain | grep "/Active Directory" | tail -n 1 | sed -n -e 's/^.*Directory///p' | tr -d '"')
CompName=$(/usr/sbin/dsconfigad -show | awk '/Computer Account/{print $NF}')

dn=$(/usr/bin/dscl "/Active Directory/$DomainName/All Domains" read /Computers/"$CompName" dsAttrTypeNative:distinguishedName | cut -f2- -d ' ')
echo "<result>$dn</result>"
exit 0