Custom Computer Name Help

mwu1876
Contributor

Any good scriptures that can help me create a script to rename computers based on the first two letters of the user's last name and then the last 6 of the serial? I've look around and there are lots of various scripts but nothing that does something similar where I can piece it together. Plus, I'm still learning my way around the scripts.

10 REPLIES 10

DBrowning
Valued Contributor II

something like this should work:

#!/bin/sh

loggedInUser=$( echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ && ! /loginwindow/ { print $3 }' )

sn=$(system_profiler SPHardwareDataType | awk '/Serial/ {print $4}' | cut -c 6-)
lastNameLetters=$( dscl . -read /Users/$loggedInUser RealName | cut -d: -f2 | sed -e 's/^[ 	]*//' | grep -v "^$" |awk '{print $NF}' | cut -c -2)

computerName=$lastNameLetters$sn

echo $computerName


networksetup -setcomputername "$computerName"
scutil --set LocalHostName "$computerName"
scutil --set HostName "$computerName"
sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.smb.server NetBIOSName "$computerName"

mwu1876
Contributor

Thanks! Giving it a try.

mwu1876
Contributor

Doesn't seem to work. Anything special I need to do?

DBrowning
Valued Contributor II

@mwu1876 How are you running it?

mwu1876
Contributor

@ddcdennisb I added the script to the settings and then created a policy to execute that script. The policy log shows that it executed but nothing changed.

DBrowning
Valued Contributor II

@mwu1876 Where are you looking to see the change? If you are only looking in the Jamf Pro Web interface, you'll need to wait for an inventory update to see the new name.

tlarkin
Honored Contributor

You can use structured data from the plist output of both dscl and system_profiler to ensure you are getting the right data. Here is a 5 minute Python example I whipped up. Also, if you run the script for the device to show the name in jamf it must do a recon. Jamf Pro doesn't know local device state until inventory is updated, FYI

#!/usr/bin/python

# import modules
from SystemConfiguration import SCDynamicStoreCopyConsoleUser
from Foundation import NSHomeDirectoryForUser
import plistlib
import subprocess

# vars

USER, UID, GID = SCDynamicStoreCopyConsoleUser(None, None, None)
USERPATH = NSHomeDirectoryForUser(USER)

# functions

def build_computername(username):
    # system profiler command
    cmd = ['/usr/sbin/system_profiler', 'SPHardwareDataType', '-xml']
    proc1 = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out1, err1 = proc1.communicate()
    data = plistlib.readPlistFromString(out1)
    serial = data[0]["_items"][0]["serial_number"][-6:]
    dsclcmd = ['/usr/bin/dscl', '-plist', '.', 'read', username, 'RealName']
    proc2 = subprocess.Popen(dsclcmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out2, err2 = proc2.communicate()
    udata = plistlib.readPlistFromString(out2)
    lastn = udata['dsAttrTypeStandard:RealName'][0].split()[1][0:2].upper()
    final_name = str(lastn + serial)
    return final_name


def set_compuptername(name):
    """set the computer name to the serial number of the Mac"""
    options = ["HostName", "ComputerName", "LocalHostName"]
    for option in options:
        subprocess.call(["scutil", "--set", option, name])

name = build_computername(USERPATH)
set_compuptername(name)

tlarkin
Honored Contributor

Also, you should always test locally before you toss it into jamf, it could save you some headaches

mwu1876
Contributor

Thanks. I added an update inventory to the same policy and assumed that would work but it didn’t. I had to do a manual recon and then it showed. Works now thanks!!

sdagley
Esteemed Contributor II

As an FYI, the jamf binary has a setComputerName verb:

Usage:   jamf setComputerName [-target <target volume>] [-name <name>]
         [-useMACAddress] [-useSerialNumber] [-suffix <suffix>]
         [-prefix <prefix>] [-fromFile <path to file>]


     -target         The target drive to set the name on

     -name           The new name for the computer

     -useMACAddress      Generate the name using the MAC Address

     -useSerialNumber    Generate the name using the Serial Number

     -prefix         Add this prefix to the MAC Address or Serial Number

     -suffix         Add this suffix to the MAC Address or Serial Number

     -fromFile       The path to a CSV file containing the computer's MAC Address or Serial Number followed by the desired name

(Credit to a classmate in a recent Jamf 300 course)