Domain Join truncate to 15 characters

NYBGIT
New Contributor III

Hi everyone,

I found this script which allow me to join Macs to the domain. I'm having an issue where our machines are named with more than 15 character and this is where the issue lies.

My Work is:
1. Enroll device
2. Rename the device to our name scheme (BuildingPrefix - Serialnumber)
3. Reboot and run the Domain join script below.

Does anyone have a script like this but truncates to the first 15 characters. Configuration profile does this but it installs the profile immediately joining the machine to the domain with the incorrect computer name.

####################################################################

Author: Scott Blake

Modified: 2017-01-25

SBind the machine to an Active Directory Domain using the first 5 or 6

characters of the Computer Name to determine what OU to use and adding

administrative groups where necessary.

####################################################################

Changelog

Version 1.0 - Scott Blake

Initial script

Version 1.1 - Scott Blake

Update styling to match other scripts in the repository

####################################################################

Variables

Active Directory domain

domain="domain"

Username/Password used to perform binding

username="ADUsername"
password="ADUserPassword"

Default OU to put machines when there is no matching prefix

ou="SPECIFY OU"

Define groups array - groups will be given admin privileges

groups=("Domain Groups")

####################################################################

Additional Variables - Do Not Edit

olddomain=$( dsconfigad -show | awk '/Active Directory Domain/{print $NF}' )
computername=$( scutil --get ComputerName )
adcomputerid=$( echo "${computername}" | tr [:lower:] [:upper:] )
prefix="${adcomputerid:0:6}"

####################################################################

Code

echo "Using computer name '${adcomputerid}'..."
echo ""

Unbind if already bound

If the domain is correct

if [[ "${olddomain}" == "${domain}" ]]; then # Check the id of a user id -u "${username}" > /dev/null 2>&1

# If the check was successful... if [[ $? == 0 ]]; then echo -n "This machine is bound to AD. Unbinding..."

# Unbind from AD dsconfigad -remove -force -u "${username}" -p "${password}"

# Re-check the id of a user id -u "${username}" > /dev/null 2>&1

# If the check was successful... if [[ $? == 0 ]]; then echo "Failed (Error code: 1)" exit 1 else echo "Success" echo "" fi fi
fi

Convert ComputerID prefix to OU ##

echo "Checking for '${prefix}' prefix..."

case "${prefix}" in # First 6 chars match ABCDEF, ABCDEG, or ABCDEH # Also add AlphaBetaCharlie-Technicians security group as admins "ABCDEF"|"ABCDEG"|"ABCDEH") ou="OU=Computers,OU=DeltaEcho,OU=AlphaBetaCharlie" groups+=("AlphaBetaCharlie-Technicians") ;; # First 6 characters match XYZ123 # This OU doesn't have secondary on-site support, so don't add a group "XYZ123") ou="OU=Computers,OU=XrayYankeeZulu" ;; "XYZLAB") ou="OU=Lab,OU=Computers,OU=XrayYankeeZulu" ;; *) # Nothing found, try the prefixes with 5 characters prefix="${prefix:0:5}" echo "Checking for '${prefix}' prefix..."

case "${prefix}" in "ABCYZ") ou="OU=Computers,OU=AlphaBetaCharlie" groups+=("AlphaBetaCharlie-Technicians") ;; esac
esac

Append domain to $ou and replace all '.' with ',DC='

ou="${ou},DC=${domain//./,DC=}"

Display OU string

echo "Using '${ou}' OU..."
echo ""

Display all groups

echo "Adding administrative privileges to..."
for group in "${groups[@]}"; do echo $group;
done
echo ""

Combine array into comma separated list

groupList=$( printf ",%s" "${groups[@]}" )
groupList="${groupList:1}"

Perform bind

dsconfigad -add "${domain}" -username "${username}" -password "${password}" -computer "${adcomputerid}" -useuncpath enable -mobile enable -mobileconfirm disable -shell /bin/bash -ou "${ou}" -force -groups "${groupList}"

3 REPLIES 3

NYBGIT
New Contributor III

How do i modify this line to choose the first 15 characters?

computeridtmp="default"
LEN=$(echo ${#adcomputerid})

if [ $LEN -lt 15 ]; then
        echo "ComputerID "$adcomputerid " has 15 characters or less and is therefore suitable for AD-Binding. It is $adcomputerid"
        computeridtmp=$adcomputerid
else
        echo "ComputerID "$adcomputerid " has 16 or more characters and needs to be modified for AD-Binding."
    #echo "Removing any -"
        computeridtmp=${adcomputerid///}
        LEN=$(echo ${#computeridtmp})
        if [ $LEN -lt 15 ]; then
            echo "ComputerID "$computeridtmp" has now 15 characters or less and is therefore suitable for AD-Binding."
        else
            echo "Only using the last 15 characters of the Computer name to be able to bind to AD."
            computeridtmp=${computeridtmp}
        fi
        echo "Cropped Computername to "$computeridtmp

NYBGIT
New Contributor III

Never mind found it online.

NYBGIT
New Contributor III

Hi Everyone,

i found this script to join machines to the domain. I modified it to only use the first 15 characters of the Machine name.

#!/bin/sh

## Script to automate OD and AD Binding to the Servers
## Script written by Marc Horat, URZ Basel, 11.6.2010

# With the use of the following sources as inspiration:

# http://www.howtomac.co.uk/?p=247
#####################################
#Created by Ross Hamilton
#Clock restart / Remove existing settings
#Join to Open Directory and Active Directory
#
#####################################

# Bombich's AD-Bind Script:
# This script binds to AD and configures advanced options of the AD plugin
# As this scripts contains a password, be sure to take appropriate security
# precautions
# 
# A good way to run this script is to set it as a login hook on your master machine
# Because it only needs to be run once, the last thing this script does is to delete
# itself. If you have another login script that you typically run, include the 
# script on your master machine, and indicate its path in the "newLoginScript"
# variable.
#
# If running this as a one-time login hook to bind to AD after imaging,
# be sure to enable auto-login (for any local user) before creating your master image



############ Begin

# Host-specific parameters
# computerid should be set dynamically, this value must be machine-specific
# This value may be restricted to 19 characters! The only error you'll receive upon entering
# an invalid computer id is to the effect of not having appropriate privileges to perform the requested operation
#computerid=`/sbin/ifconfig en0 | awk '/ether/ { gsub(":", ""); print $2 }'` # MAC Address
#computerid=`hostname | sed 's/.unibas.ch//'`
#computerid=`/usr/sbin/scutil --get LocalHostName | cut -c 1-19` # Assure that this will produce unique names!
#computerid=`/usr/sbin/scutil --get LocalHostName`
computerid=`scutil --get ComputerName`
adcomputerid=`echo $computerid | tr [:lower:] [:upper:]`


# These variables probably don't need to be changed
nicAddress=`ifconfig en0 | grep ether | awk '{print $2}'`
check4OD=`dscl localhost -list /LDAPv3 | grep -n 1 | sed 's/1://' | sed 's/2://'`
check4ODacct=`dscl /LDAPv3/$check4OD -read Computers/"${computerid}" RealName | cut -c 11-`
check4AD=`dscl /Search -read / CSPSearchPath | grep /Active`
osversionlong=`sw_vers -productVersion`
osvers=${osversionlong:3:1}


#####################AD CONFIG#############################
# Standard parameters
domain="DOMAIN"            # fully qualified DNS name of Active Directory Domain
udn="USERNAME"            # username of a privileged network user
password="PASSWD"                    # password of a privileged network user
ou="OU=CONTAINER FOR MACHINE DROP"        # Distinguished name of container for the computer

# Advanced options AD Plugin
alldomains="disable"            # 'enable' or 'disable' automatic multi-domain authentication
localhome="disable"            # 'enable' or 'disable' force home directory to local drive
protocol="smb"                # 'afp' or 'smb' change how home is mounted from server
mobile="disable"            # 'enable' or 'disable' mobile account support for offline logon
mobileconfirm="disable"        # 'enable' or 'disable' warn the user that a mobile acct will be created
useuncpath="enable"            # 'enable' or 'disable' use AD SMBHome attribute to determine the home dir
user_shell="/bin/bash"        # e.g., /bin/bash or "none"
preferred="-nopreferred"    # Use the specified server for all Directory lookups and authentication
                            # (e.g. "-nopreferred" or "-preferred ad.server.edu")
admingroups="DOMAIN GROUPS FOR ADMIN PRIV"                # These comma-separated AD groups may administer the machine (e.g. "" or "APPLEmac admins")
packetsign="allow"            # allow | disable | require
packetencrypt="allow"        # allow | disable | require
passinterval="14"            # number of days
namespace="domain"            # forest | domain

# Login hook setting -- specify the path to a login hook that you want to run instead of this script
#newLoginHook="PATHTOLOGINHOOK"        # e.g., "/Library/Management/login.sh"


#####################END AD CONFIG#############################

#Time Sync

#Restart ntpdate
StartService ()
{
if [ "${TIMESYNC:=-YES-}" = "-YES-" ] && ! GetPID ntpd > /dev/null; then

CheckForNetwork

if [ -f /var/run/NetworkTime.StartupItem -o "${NETWORKUP}" = "-NO-" ]; then exit; fi
touch /var/run/NetworkTime.StartupItem

echo "Starting network time synchronization"

# Synchronize our clock to the network’s time,
# then fire off ntpd to keep the clock in sync.
ntpdate -bvs
ntpd -f /var/run/ntp.drift -p /var/run/ntpd.pid
fi
}

#List existing Directories
echo "This computer is bound to the following Active Directory Services:"
dscl /Search -read / CSPSearchPath | grep /Active

sleep 5
# Removing any existing directory bindings

# Removing any existing directory bindings

if [ "${check4ODacct}" == "${computerid}" ]; then
    echo "This machine already has a computer account on "${oddomain}"."
    if [ "$oldComputerGroup" != "" ]; then
        echo "Removing entry from group $oldComputerGroup"
        dscl -u "${odAdmin}" -P "${odPassword}" /LDAPv3/"$check4OD" -delete /ComputerGroups/"$oldComputerGroup" GroupMembership "${computerid}"
    fi
    echo "Removing Computer entry $computerid in OD"
    dscl -u "${odAdmin}" -P "${odPassword}" /LDAPv3/"$check4OD" -delete /Computers/"${computerid}"
fi
#A second time..
if [ "${check4ODacct}" == "${computerid}" ]; then
    echo "This machine already has a computer account on "${oddomain}"."
    if [ "$oldComputerGroup" != "" ]; then
        echo "Removing entry from group $oldComputerGroup"
        dscl -u "${odAdmin}" -P "${odPassword}" /LDAPv3/"$check4OD" -delete /ComputerGroups/"$oldComputerGroup" GroupMembership "${computerid}"
    fi
    echo "Removing Computer entry $computerid in OD"
    dscl -u "${odAdmin}" -P "${odPassword}" /LDAPv3/"$check4OD" -delete /Computers/"${computerid}"
fi


sleep 5

echo "Removing any existing AD-Binding to "$check4AD""
dsconfigad -f -r -u $udn -p "$password"
dscl /Search -delete / CSPSearchPath "$check4AD"
dscl /Search/Contacts -delete / CSPSearchPath "$check4AD"
dscl /Search -delete / CSPSearchPath "$check4AD"
sleep 5

echo "Killing DirectoryService"
killall DirectoryService

sleep 5

#############################################################
#AD
#############################################################

# Activate the AD plugin
defaults write /Library/Preferences/DirectoryService/DirectoryService "Active Directory" "Active"
plutil -convert xml1 /Library/Preferences/DirectoryService/DirectoryService.plist

computeridtmp="default"
LEN=$(echo ${#adcomputerid})

if [ $LEN -lt 15 ]; then
        echo "ComputerID "$adcomputerid " has 15 characters or less and is therefore suitable for AD-Binding. It is $adcomputerid"
        computeridtmp=$adcomputerid
else
        echo "ComputerID "$adcomputerid " has 16 or more characters and needs to be modified for AD-Binding."
    #echo "Removing any -"
        computeridtmp=${adcomputerid///}
        LEN=$(echo ${#computeridtmp})
        if [ $LEN -lt 15 ]; then
            echo "ComputerID "$computeridtmp" has now 15 characters or less and is therefore suitable for AD-Binding."
        else
            echo "Only using the last 15 characters of the Computer name to be able to bind to AD."
            computeridtmp=${computeridtmp:0:15}
        fi
        echo "Cropped Computername to "$computeridtmp 



fi

# Bind to AD
dsconfigad -f -a $computeridtmp -domain $domain -u $udn -p "$password" -ou "$ou"

# Configure advanced AD plugin options
if [ "$admingroups" = "" ]; then
    dsconfigad -nogroups
else
    dsconfigad -groups "$admingroups"
fi

dsconfigad -alldomains $alldomains -localhome $localhome -protocol $protocol 
    -mobile $mobile -mobileconfirm $mobileconfirm -useuncpath $useuncpath 
    -shell $user_shell $preferred -packetsign $packetsign -packetencrypt $packetencrypt 
    -passinterval $passinterval -namespace $namespace

sleep 10


# Add the OD & AD node to the search path
if [ "$alldomains" = "enable" ]; then
    csp="/Active Directory/All Domains"
else
    csp="/Active Directory/$domain"
fi

echo "Finished AD Binding."

echo "Now bound to AD Domain:"
dscl localhost -list "/Active Directory"
echo "With Search Path entries:"
dscl /Search -read / CSPSearchPath | grep /Active

echo "Restarting Directory Services."

# Restart DirectoryService (necessary to reload AD plugin activation settings)
killall DirectoryService

# Kill loginwindow to return to the login screen
killall loginwindow