Script to rename Mac

macboy
Contributor

I am running a script that will ask the end user to enter the machine name. It will not work through Casper (remotely or in a policy) but will work fine if I run it locally. Any ideas why it may not be running? I have included the script below.

!/bin/bash

ComputerName=`/usr/bin/osascript <<EOT
tell application "System Events" activate set ComputerName to text returned of (display dialog "Please Input New Computer Name" default answer "" with icon 2)
end tell
EOT`

Set New Computer Name

echo $ComputerName
scutil --set HostName $ComputerName
scutil --set LocalHostName $ComputerName
scutil --set ComputerName $ComputerName

echo Rename Successful

exit

Very odd the script runs fine when ran locally through the terminal. But stalls and never runs and never errors out when ran through a policy or through remote.

Thank you.

1 ACCEPTED SOLUTION

mm2270
Legendary Contributor II

The problem is the Applescript (osascript) call in your script. Applescript messages that call for user interaction don't work well when they are done via a root session, the way a Casper Suite policy will do. Its not Casper's fault. Its the OS doing its job of protecting the user space. Essentially osascript commands called by root can't display to the logged in user (unless the user logged in is root of course)

There are a few ways around it. You can try calling the command as the user with a sudo -u $loggedInUser type syntax, but sometimes even this doesn't work. The more reliable way would be to use launchctl asuser (10.10 & 10.11), orlaunchctl bsexec (10.9 and below)

Another way would be to ditch Applescript and use something like cocoaDialog, which doesn't run into the same restrictions. But this would mean deploying a custom tool to your Macs. You may not want to do that, and I'd understand. Though cocoaDialog, while old now, is still very useful in many regards.

For using launchctl, you can try something like this. Keep in mind this will only work on 10.10 and 10.11. The 'asuser' syntax doesn't exist in earlier OSes.

#!/bin/bash

loggedInUser=$(stat -f%Su /dev/console)
loggedInUID=$(id -u "$loggedInUser")

ComputerName=$(/bin/launchctl asuser "$loggedInUID" sudo -iu "$loggedInUser" "/usr/bin/osascript -e 'tell application "System Events" to set ComputerName to text returned of (display dialog "Please Input New Computer Name" default answer "" with icon 2)'")

echo "$ComputerName"

Just fill out the remainder of the script with the rest of what you wrote. The above should work, but I only wrote this right here and didn't test it, so give it a try.

View solution in original post

55 REPLIES 55

k84
New Contributor III

@larry_barrett by any chance did this work as a policy, if you have tested this in that method?

danlaw777
Contributor

Hi, We just had our jamf jumpstart this week, and this post piqued my interest. we use the machine serial numbers as part of the name which are preceded by our location codes. I have dug deep into scripting yet, but has anyone been able to accomplish something like this?

larry_barrett
Valued Contributor

@k84 I didn't try, but when I try to run it via terminal (using sudo jamf policy) this is the message from the policy logs:

Executing Policy Name Computer
Running script Set Computer Name...
Script exit code: 0
Script result: 33:41: execution error: An error of type -10810 has occurred. (-10810)

There was an error.

     You must specify a computer name. Use the -name flag

I never did get the dialogue box to enter a name.

Tribruin
Contributor III
Contributor III

See if this version works.

#!/bin/sh
#  Name Your Computer.sh
#  
#
#  Created by Carey-Peterson, Rob on 10/25/19.
#  


tag=$(/usr/bin/osascript << EOD
text returned of (display dialog "What is your Computer name?" default answer "" buttons {"Continue"} default button 1)
EOD
)


#This takes the data collected from the user and sets it as the Computer Name and submits the name to the Jamf API

deviceName="$tag"

#set all the name in all the places
/usr/local/bin/jamf setcomputername -name "$deviceName"
/usr/local/bin/jamf recon

Tribruin
Contributor III
Contributor III

@danlaw777 What is your hang-up? Trying to get the Serial Number or something else? here is how you can get the serial number in a script:

#!/bin/sh

serialNumber=$(system_profiler SPHardwareDataType | awk -F': ' '/Serial Number/ {print $2}')

After that, you can just append your location code.

k84
New Contributor III

@RBlount that worked when running it in terminal as a custom event.

Will try it again when the Mac gets placed into the JSS at the enrolment stage. The script I used used previously worked but when my second enrolment trigger kicks in to install the base apps & then bind to AD for some odd reason binded the machine with a different Host Name although when checking system preferences > sharing the machine was what I entered when the dialogue box popped up.

Will let you know how I get on.

k84
New Contributor III

Hi @RBlount so when running it as a policy on first enrolment I get the this error

You must specify a computer name. Use the -name flag

Tribruin
Contributor III
Contributor III

When is the enrollment policy running? If the enrollment policy is kicking off while the setup or login screen is active, the user will never see the prompt to enter the computer name. if you can add the following to your script:

#!/bin/sh
set -x

Then we can see is happen in the script by looking at the policy logs.

cwwirth
New Contributor II

Hi @RBlount, I'm trying to work with your script above and coming across a minor hiccup. If I run it as-is on Catalina from a .sh file invoked manually through Terminal, it works -- but when it gets to the step where it executes the jamf setcomputername process, it asks for a password within the Terminal window. My hope is to be able to kick this off via a policy, so the Terminal window won't be available. I've modified the script to invoke /usr/bin/scutil to do the renaming instead:

/usr/sbin/scutil --set ComputerName "${deviceName"
/usr/sbin/scutil --set LocalHostName "${deviceName"
/usr/sbin/scutil --set HostName "${deviceName"

...which, thankfully, brings up a GUI prompt for the user to enter a password. Problem is, it's prompting three times (once for each of those lines). Any ideas on how I can cut this down to one auth prompt (or get the jamf setcomputername command to issue its auth prompt in a window)?

catesr
New Contributor III

Hi. I don't know if this helps at all (kind of a scripting novice) but this is what we use. It shows up in SS right after the machine set up is complete. We throw an "MBA-" in from of our machine names but it can be modified. Also it works on both 10.14 and 10.15.

!/bin/bash

Script to prompt for ComputerName, Set Name and Inventory in JAMF

assetTag=$(osascript -e 'text returned of (display dialog "Please type in the Asset Tag Number: "default answer "Enter Number Here" buttons {"Submit"} default button 1)')
computerName=MBA-$assetTag

Set Computer Name

scutil --set HostName $computerName
scutil --set LocalHostName $computerName
scutil --set ComputerName $computerName

Run Recon

jamf recon -assetTag $assetTag

JarvisUno
Contributor II

Not sure if this adds any value but I have a policy that ties x3 separate scripts creating the computer name for my Organization.
0b95f16cd9cc450f886a1ab7af004991

The rename-computer.py script pulls from a .CSV that is located anywhere of your choosing. That file has a list of all your computers by Serial Number and what you want the computer name to be.

You can read all about it here: Automatically Renaming Computers from a Google Sheet with Jamf Pro

I have spoken with @haircut some time ago that stated he may or may not change the script to a .zsh in the future but no developments there. You can always subscribe to his GitHub and watch for any changes like I have. But as of right now this has been working flawlessly with every version of MacOS I have tested including 10.15.2

Xerendor
New Contributor II

Hello folks,

I've been looking to simplify the host naming step for the DEP workflow and for the IT support functions. Now, only part that eludes me in Applescript is how have I could have more describing way for locations as standard user does not understand what the prefix means.

See below:

#!/bin/bash

## Rename device - draft


## Set prefix value for the region

ComputerName=`/usr/bin/osascript <<EOT

set AssetTag to text returned of (display dialog "please insert asset tag" default answer "" with icon 2)

tell application "System Events"
activate
set ComputerLocations to {"BE1MCL", "NL1MCL", "NL2MCL","PL1MCL"}
set ComputerName to choose from list ComputerLocations with prompt "Select your office location:" default items {"NL1MCL"}
end tell
EOT`

## User input for the security sticker/asset tag
AssetTag=`/usr/bin/osascript <<EOT
tell application "System Events"
activate

set AssetTag to text returned of (display dialog "Please insert the company provided asset tag" default answer "" with icon 2)
end tell
EOT`

##Set New Computer Name

echo $ComputerName
echo $AssetTag
sudo scutil --set HostName $ComputerName-$AssetTag
sudo scutil --set LocalHostName $ComputerName-$AssetTag
sudo scutil --set ComputerName $ComputerName-$AssetTag
sudo /usr/local/bin/jamf setComputerName -name $ComputerName-$AssetTag

echo Rename Successful

cdenesha
Valued Contributor II

@Xerendor If you only have the four locations, then you could prompt for the actual location name in English for the user to choose, then do an IF THEN set of statements to get the ComputerName you want.

josh_glenn
New Contributor II

Could use some help on ours. Basically, we need it unbind the Mac once logged in, pop up and ask for the Asset Tag number. Once it has the Asset Tag number I want it to then ask if the computer is mobile or desktop. Once that is determined, it'll add -M to the Asset Tag number to name a laptop, or leave the name without the -M if the asset is a Desktop. After all this it triggers my bind script and rebinds with the correct name.

I have gotten the script to work just fine (including adding the -M to the name) without the if/else statement but once I add the if/else statement it hangs on Running in Self Service. Unfortunately, I am just not familiar enough with if/then statements to know what I am doing wrong.

Here is my script:

```
# Unbind the AD

sudo dsconfigad -force -remove -u johndoe -p nopasswordhere

# Prompt User for Asset Tag

assetTag=$(`/usr/bin/osascript <<EOT
tell application "System Events"
    activate
        set assetTag to text returned of (display dialog "Please Enter the Asset Tag Number for this Device." default answer "")
end tell
EOT`
)

# Prompt User for Asset Type

assetType=$(`/usr/bin/osascript <<EOT
tell application "System Events" 
    activate
        set assetType to text returned of (display alert "Is This Asset a Laptop?" buttons {"Yes", "No"})
end tell
EOT`
)


# Name According to Asset Type

assetName=$(`/usr/bin/osascript <<EOT
if assetType contains "Yes" then 
    set assetName to (assetTag as text)'-M'
else if assetType contains "No" then
    set assetName to (assetTag as text)
end if
EOT`
)

scutil --set HostName $assetName
scutil --set LocalHostName $assetName
scutil --set ComputerName $assetName

# Submit New Name to Jamf

sudo jamf setComputerName -name $assetName

# Submit Asset Tag to Jamf

sudo jamf recon -assetTag $assetTag

# Update Jamf inventory data

sudo jamf recon

# Notify User of Rename Success

`/usr/bin/osascript <<EOT
tell application "System Events" 
activate
display dialog "Rename Successful!"
end tell
EOT`

```

josh_glenn
New Contributor II

My previous script - the one that worked but did not determine between Laptop/Desktop is this:

Unbind the AD

sudo dsconfigad -force -remove -u johndoe -p nopasswordhere

Prompt User for Asset Tag

while :; do

assetTag=$(osascript -e 'tell application "System Events" to display dialog "Please Enter the Asset Tag Number for this Device." default answer ""' -e 'text returned of result' 2>/dev/null)

Set Asset Name

assetName=$(echo $assetTag)'-M'

Tell System Events to loop if input is empty

if [[ -z "$assetTag" ]]; then

# The user left the name blank osascript -e 'Tell application "System Events" to display alert "You must enter an Asset Tag Number. Please try again." as warning' >/dev/null

# Continue loop to prompt again. else # Valid input: exit loop and continue. break fi
done

scutil --set HostName $assetName
scutil --set LocalHostName $assetName
scutil --set ComputerName $assetName

Make sure Jamf Updates with New Name

sudo jamf setComputerName -name $assetName

Submit Asset Tag to Jamf

sudo jamf recon -assetTag $assetTag

Update Jamf inventory data

sudo jamf recon

Notify User of Rename Success

osascript -e 'Tell application "System Events" to display dialog "Rename Successful!"'

Mauricio
Contributor II

@josh.glenn

You can get the model from the Mac, no need to ask the user for it.
As you are running a bash/shell script there is no need to run the ifs in AppleScript

Modified script:

``` # Unbind the AD sudo dsconfigad -force -remove -u johndoe -p nopasswordhere # Prompt User for Asset Tag assetTag=$(`/usr/bin/osascript <<EOT tell application "System Events" activate set assetTag to text returned of (display dialog "Please Enter the Asset Tag Number for this Device." default answer "") end tell EOT` ) # Name According to Asset Type # looking for Book or book. hdModel=$(sysctl hw.model | awk 'BEGIN {} $2~/.(b|B)ook./{print "M"}') # if it is a "book" add the '-M' into the assetName if [ "$hdModel" == "M" ];then assetName="$assetName-M" fi scutil --set HostName $assetName scutil --set LocalHostName $assetName scutil --set ComputerName $assetName # Submit New Name to Jamf sudo jamf setComputerName -name $assetName # Submit Asset Tag to Jamf sudo jamf recon -assetTag $assetTag # Update Jamf inventory data sudo jamf recon # Notify User of Rename Success `/usr/bin/osascript <<EOT tell application "System Events" activate display dialog "Rename Successful!" end tell EOT`

Regards