Change Mac hostname to match computer name

ooshnoo
Valued Contributor

Yo..

We have many Mac's whose hostname doesn't match their computer name.

Is there any easy script we could use that will 1...get the computer name and then 2...use scutil to set the hostname to match the computer name?

Thanks!

4 REPLIES 4

pkleiber
Contributor

Something like this maybe:

#!/bin/sh
## Get ComputerName
HOST=$(scutil --get ComputerName)

## Set HostName and LocalHostname
scutil --set HostName "$HOST"
scutil --set LocalHostName "$HOST"

I did what this @pkleiber has. 

You can also create a smart group using an extension attribute. 

What I did for the script in the extension attribute is add this script and set Input Type to String:

#!/bin/sh

##set variables to check computername and hostname on the device
HostName=$(scutil --get HostName)
CompName=$(scutil --get ComputerName)

##function to check if hostname is set
if [[ "$HostName" != "$CompName" ]]; then
#If hostname does not match computer name
	echo "<result>Not Set</result>"
else
#If host name is = to computer name
	echo "<result>Set</result>"
fi

 This script will output values "Set" is hostname matches computer name or "Not Set" if it doesn't match. 

When you have your devices that do not match. You can target a policy with this script to change the hostname to the computer name:

#!/bin/sh

##Set variable to get computer name
CompName=$(scutil --get ComputerName)

##set Hostname to Computername
scutil --set HostName "$CompName"

##Flush DNS on device (optional, uncomment if you want to flushDNS)
##dscacheutil -flushcache

##Updates user passwords with preboot (Optional)
##diskutil apfs updatePreboot /

##sends updated device information to Jamf
jamf recon

What criteria did you use to create a smart group for them not to be "Not set" for this to apply to

emanueldiaz_09
New Contributor III

I use the first code above as an extension attribute. For the criteria you can use what's in the <result> tag. Either:

Not Set

or

Set

Depending on whether you want to grab devices that have hostname set or devices that do not. I used Not Set so I can see the devices that do not have their hostname matching Computer name then use the second script in a policy to target those computers.