Script for naming computer as LDAP user

jwzg
New Contributor

I was able to use a script found here to assign a computer based on LDAP name. How about a script for changing the name of the computer to the LDAP user proper name (e.g. Lastname Firstname) or something similar?

4 REPLIES 4

mm2270
Legendary Contributor III

That should be possible, but... you may end up with some weird names since the full LDAP name can contain odd characters like commas, or apostrophes in them. You'd probably have to pass the name through sed to replace spaces, punctuation marks and other stuff to make it into a more appropriate computer name.

Kennedy
New Contributor II

By default (ie when machines are imaged) we name the machine by the MAC Address of the Wifi adapter. Then once a user has signed into that machine, we write their username to a text file which we call a breadcrumb. We do this with a login policy. We then grab their username into an extension attribute by reading this breadcrumb and excluding machines that already have the breadcrumb from the policy along with any admin users, etc. We do this with the following script:

#!/bin/bash

#log the output of the script to the jamf.log for easy viewing
logfile=/var/log/jamf.log;
exec >> $logfile 2>&1;




#------------------------------     
#-------BEGIN VARIABLES--------
#------------------------------ 

scriptname="populate_username.sh";
breadcrumb="/Library/BCGS/breadcrumb_username_populated.txt";
currentUser=`defaults read /Library/Preferences/com.apple.loginwindow lastUserName` >/dev/null 2>/dev/null

#set LoggedInUser as the current user
if [ `ls -l /dev/console | cut -d " " -f 4` == "root" ]
then
    #script is run at login, so the user is the $3 variable
    LoggedInUser=$3
else
    #script is run as self service, so the user is not sent to the script
    LoggedInUser=`ls -l /dev/console | cut -d " " -f 4`
fi

#------------------------------     
#-------END VARIABLES----------
#------------------------------



echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:   "
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: ------------------------------------------------------"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: --- Starting $scriptname"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:   "
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: Script variables:" 
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:    $LoggedInUser =  $LoggedInUser"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:    $currentUser =  $currentUser"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:"

if [ -f "$breadcrumb" ]
then
    # We should skip running this script, as it looks like it has already run at a previous reboot.
    # In theory this should never occur, as it should be exlcuded in the policy, so this is a second
    # measure.
    echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: Skipped populating the username as we have already done this."
else
    # Grab the username of the user that last logged in (current user).
    # This will only return an accurate username the second time the user logs in.
    echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: Username is '$currentUser'."

    if [ $LoggedInUser == $currentUser ]
    then
        # Usernames are the same, so lets proceed.
        # Submit an inventory report and include the current user to be written to the
        echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: Usernames are the same ($LoggedInUser, $currentUser)"
        echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: Running 'jamf recon -endUsername $LoggedInUser."
        jamf recon -endUsername $currentUser >/dev/null 2>/dev/null

        # Create the breadcrumb so we know not to run the script again
        echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: Creating the breadcrumb."
        echo $LoggedInUser >> $breadcrumb 

        # Run recon again to pick up the breadcrumb extension attribute
        echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: Running jamf recon for a second time."
        jamf recon >/dev/null 2>/dev/null
    else
        # Do not write the breadcrumb, then the script will run next time
        echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: Usernames are not the same ($LoggedInUser, $currentUser)"
    fi
fi


echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:   "
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: --- Finished $scriptname -----------------------------"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: ------------------------------------------------------"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:   "

exit 0

Then we name our computers using their usernames from this breadcrumb file, but replace the dot with an underscore. Careful allowing dots in the computer name as you might run into some interesting DNS entries. The following script is used to rename the computer:

#!/bin/bash

#log the output of the script to the jamf.log for easy viewing
logfile=/var/log/jamf.log;
exec >> $logfile 2>&1;




#------------------------------     
#-------BEGIN VARIABLES--------
#------------------------------ 

scriptname="rename_computer_to_username.sh";
breadcrumb="/Library/BCGS/breadcrumb_username_populated.txt";
if [ -f $breadcrumb ]
then
    breadcrumb_user=$(head -n 1 $breadcrumb)
else
    breadcrumb_user=""
fi

#set LoggedInUser as the current user
if [ `ls -l /dev/console | cut -d " " -f 4` == "root" ]
then
    #script is run at login, so the user is the $3 variable
    LoggedInUser=$3
else
    #script is run as self service, so the user is not sent to the script
    LoggedInUser=`ls -l /dev/console | cut -d " " -f 4`
fi

#------------------------------     
#-------END VARIABLES----------
#------------------------------






echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:   "
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: ------------------------------------------------------"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: --- Starting $scriptname"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:   "
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: Script variables:" 
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:    $LoggedInUser =  $LoggedInUser"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:    $breadcrumb =  $breadcrumb"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:    $breadcrumb_user = $breadcrumb_user"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:"

if [ -z $breadcrumb_user ]
then
    #user variable is blank
    echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: User breadcrumb is blank, doing nothing."
else
    echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: Setting computer name to $breadcrumb_user."
    jamf setComputerName -name ${breadcrumb_user/./_} >/dev/null 2>/dev/null
    echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: Running jamf recon."
    jamf recon >/dev/null 2>/dev/null
fi

echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:   "
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: --- Finished $scriptname"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]: ------------------------------------------------------"
echo "`date +"%a %b %d %X"` `hostname` jamf[script-$scriptname]:   "

exit 0

I'm sure you can modify the above to work for you. Hope it helps!

Simmo
Contributor II
Contributor II

This can be done using the JSS api

#!/bin/sh

jssUser=apiuser
jssPass=apipassword

serial=$(ioreg -c IOPlatformExpertDevice -d 2 | awk -F" '/IOPlatformSerialNumber/{print $(NF-1)}')

response=$(curl -k https://your.jss.url:8443/JSSResource/computers/serialnumber/${serial}/subset/location --user "${jssUser}:${jssPass}")
real_name=$(echo $response | /usr/bin/awk -F'<real_name>|</real_name>' '{print $2}');
user_name=$(echo $response | /usr/bin/awk -F'<username>|</username>' '{print $2}');

/usr/sbin/scutil --set ComputerName "${real_name}"
/usr/sbin/scutil --set LocalHostName "${user_name}-MBA"
/usr/sbin/scutil --set HostName "${user_name}-MBA"
dscacheutil -flushcache

pereljon
New Contributor III

Here's my namer script. It names the computer based on the user name, title, department, asset tag and computer type. Barcode1 gets used for special systems.

#!/bin/bash

CURL_OPTIONS="--silent --connect-timeout 30"
MY_API_USER="JSS_API_USERNAME"
MY_API_PASS="JSS_API_PASSWORD"
MY_JSS_BASEURL=$( /usr/bin/defaults read /Library/Preferences/com.jamfsoftware.jamf jss_url)

if [ -n "${MY_JSS_BASEURL}" ]; then
    MY_JSS_APIURL="${MY_JSS_BASEURL}JSSResource/"
    MY_SERIAL_NUMBER=$(system_profiler SPHardwareDataType | grep "Serial Number" | awk '{print $4}')
    if [ -n "${MY_SERIAL_NUMBER}" ]; then
        RESULT_XML=$(/usr/bin/curl ${CURL_OPTIONS} --header "Accept: application/xml" --request GET --user "${MY_API_USER}":"${MY_API_PASS}" "${MY_JSS_APIURL}computers/serialnumber/${MY_SERIAL_NUMBER}/subset/general&location&hardware")
        if [ -n "${RESULT_XML}" ]; then
            MANAGED=$(echo "${RESULT_XML}" | xpath "string(/computer/general/remote_management/managed)" 2> /dev/null )          
            USERNAME=$(echo "${RESULT_XML}" | xpath "string(/computer/general/remote_management/management_username)" 2> /dev/null )         
            BARCODE1=$(echo "${RESULT_XML}" | xpath "string(/computer/general/barcode_1)" 2> /dev/null )         
            COMPUTER_MODEL=$(echo "${RESULT_XML}" | xpath "string(/computer/hardware/model)" 2> /dev/null)
            ASSET_TAG=$(echo "${RESULT_XML}" | xpath "string(/computer/general/asset_tag)" 2> /dev/null)
            TITLE=$(echo "${RESULT_XML}" | xpath "string(/computer/location/position)" 2> /dev/null)
            DEPARTMENT=$(echo "${RESULT_XML}" | xpath "string(/computer/location/department)" 2> /dev/null)
            REAL_NAME=$(echo "${RESULT_XML}" | xpath "string(/computer/location/real_name)" 2> /dev/null)
            NAME_WORDS=$(echo "${REAL_NAME}" | wc -w 2> /dev/null )
            FIRST_NAME=$(echo "${REAL_NAME}" | awk '{print $1}' 2> /dev/null )
            LAST_INIT=$(echo "${REAL_NAME}" | cut -d ' ' -f ${NAME_WORDS} 2> /dev/null | cut -b 1 2> /dev/null )
            case "$DEPARTMENT" in
                'Account Management')
                    TITLE_A="ACM"
                    ;;
                *Accounting*)
                    TITLE_A="ACT"
                    ;;
                *Strategy*)
                    TITLE_A="STR"
                    ;;
                'Operations')
                    TITLE_A="OPS"
                    ;;
                'Public Relations')
                    TITLE_A="PR"
                    ;;
                *)
                    TITLE_A="???"
                    ;;
            esac
            case "$TITLE" in
                "Project Manager")
                    TITLE_B="STF"
                    ;;
                "CFO")
                    TITLE_B="CFO"
                    ;;
                "Head of"*)
                    TITLE_B="DIR"
                    ;;
                *Freelanc*)
                    TITLE_B="FRE"
                    ;;
                *"Executive Assistant"*)
                    TITLE_B="EA"
                    ;;
                *Director*)
                    TITLE_B="DIR"
                    ;;
                *)
                    TITLE_B="STF"
                    ;;
                esac
            case "$COMPUTER_MODEL" in
                *MacBook*Air*)
                    TITLE_C="MBA"
                    ;;
                *MacBook*Pro*)
                    TITLE_C="MBP"
                    ;;
                *MacBook*)
                    TITLE_C="MB"
                    ;;
                *MacPro*)
                    TITLE_C="MP"
                    ;;
                *iMac*)
                    TITLE_C="IMAC"
                    ;;
                *mini*)
                    TITLE_C="MINI"
                    ;;
                *)
                    TITLE_C="???"
                    ;;
            esac
            if [ -z "${MANAGED}" ]; then
                NEW_NAME="${MY_SERIAL_NUMBER}"
            elif [ -n "${REAL_NAME}" ] && [ -n "${BARCODE1}" ]; then
                NEW_NAME="${TITLE_A}-${BARCODE1}-${FIRST_NAME}${LAST_INIT}-${ASSET_TAG}-${TITLE_C}"
            elif [ -n "${BARCODE1}" ]; then
                NEW_NAME="${TITLE_A}-${BARCODE1}-${ASSET_TAG}-${TITLE_C}"
            elif [ -n "${REAL_NAME}" ]; then
                NEW_NAME="${TITLE_A}-${TITLE_B}-${FIRST_NAME}${LAST_INIT}-${ASSET_TAG}-${TITLE_C}"
            else
                NEW_NAME="${ASSET_TAG}-${TITLE_C}"
            fi
            sudo /usr/sbin/jamf setComputerName -name "${NEW_NAME}"
        else
            echo "Error: getting computer information from ${MY_JSS_BASEURL}" 1>&2
            exit 1
        fi
    else
        echo "Error: unable to read serial number" 1>&2
        exit 1
    fi
else
    echo "Error: unable to read jss base url" 1>&2
    exit 1
fi
exit 0

Here's the github link to the latest: https://github.com/pereljon/Casper-Scripts/blob/master/jssNamer.sht