osascript help

Cem
Valued Contributor

Hi Mac Gurus,

I need osacript help to rename the Macs. I am using Mr Larkin's cname
method to remembering Macs original names.
But now, we may need to change the Mac names. Staff would prefer GUI to do
this. My Sharing prefs is greyed out with MCX.
Only way to do this using script with jamf setComputerName or networksetup
-setcomputername commands .

So I have come up with a script. I am planning to run this with Self
service - scope to IT Admins only. But I would like a pop up window for
staff to populate the new hostname as below states as MACNAME. I know I
can do this easily with Casper Remote, but its not on the cards.

#!/bin/bash

# Please replace the MACNAME below line with the actual hostname
networksetup -setcomputername MACNAME

# This will update the original hostname record and set the permissions
mv /Library/Receipts/cname.txt /Library/Receipts/oldcname.txt
networksetup -getcomputername > /Library/Receipts/cname.txt
chmod -R 644 /Library/Receipts/cname.txt
chown -R root:wheel /Library/Receipts/cname.txt

# lets set the computer
setName=cat /Library/Receipts/cname.txt
scutil --set ComputerName ${setName}
scutil --set LocalHostName ${setName}

exit 0

Thanks for looking.

Cem

1 ACCEPTED SOLUTION

Cem
Valued Contributor

Here is the script to change the name with ease in Casper Self Service (MCX applied to disabled Sharing prefs Naming). Thanks guys for all the help with osascript.
I have tested both scripts successfully in my environment. I suggest test it before using in your environment.

--missing content--

anges their Mac names)

  1. First script will remove the Mac from AD (set as before in policy)

#!/bin/sh
# This script will remove existing Directory records and will reset Search Paths
# to /Active Directory/mycompany.com
# Tested with 10.6.x
# Remove all files containing AD bindings informations

#####################################
#Clock restart / Remove existing settings
#####################################

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

CheckForNetwork

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

echo =93Starting network time synchronization=94

# Synchronize our clock to the network=92s 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
}

# Remove exisiting
logger =93Removing existing DS Config=94

if [ ! -d "/Library/Preferences/DirectoryService/ActiveDirectory" ]; then
rm -R /Library/Preferences/DirectoryService/ActiveDirectory*
fi

if [ ! -d "/Library/Preferences/DirectoryService/DSLDAPv3PlugInConfig" ]; t
hen
rm -R /Library/Preferences/DirectoryService/DSLDAPv3PlugInConfig*
fi

if [ ! -d "/Library/Preferences/DirectoryService/SearchNode" ]; then
rm -R /Library/Preferences/DirectoryService/SearchNode*
fi

if [ ! -d "/Library/Preferences/DirectoryService/ContactsNode" ]; then
rm -R /Library/Preferences/DirectoryService/ContactsNode*
fi

if [ ! -d "/Library/Preferences/edu.mit.Kerberos" ]; then
rm -R /Library/Preferences/edu.mit.Kerberos
fi

# Restart DirectoryService (necessary to reload AD plugin activation settin
gs)
killall DirectoryService
/bin/sleep 3

exit 0

  1. Second Script will rename the Mac and the record .txt file. (set as "bef ore" and make sure it runs after the first script above - alternatively you can combined them)

#!/bin/bash

# Lets enter the computername with GUI
getname()
{
asmsg`arch -i386 /usr/bin/osascript << EOT
tell app "System Events"
Activate
set foo to text returned of (display dialog "Enter the new name of the Comp
uter" buttons {"OK"} default answer "Type Computer Name Here")
end tell
EOT`
if [ "$asmsg" "false" ]; then
getname
else
echo $asmsg
fi
}
computernamegetname

# Set the computername
networksetup -setcomputername ${computername}

# This will update the original hostname record and it will keep the old re
cord with date stamp then set the permissions
mv /Library/Receipts/cname.txt /Library/Receipts/oldcname_`date +%M-%H-%m-%
d-%y`.txt
networksetup -getcomputername > /Library/Receipts/cname.txt
chmod -R 644 /Library/Receipts/cname.txt
chown -R root:wheel /Library/Receipts/cname.txt

# lets set the computer
setNamecat /Library/Receipts/cname.txt
scutil --set ComputerName ${setName}
scutil --set LocalHostName ${setName}

# Run Recon to update JSS record with the new name
jamf recon

exit 0 ## computermame and the record updated successfully
exit 1 ## fail

  1. Then check bind to AD in Account section of the Policy to bind the Mac t o AD. I have some editing Macs here that they don=92t need to be on domain. So I have set a pop up window message saying " Please run "AD bind" from S elf Service to join this Mac to domain. Then Restart or Shut Down."

I hope this is useful=85

Cem

View solution in original post

18 REPLIES 18

Cem
Valued Contributor

I get it now.
All makes sense.

I will put it together tomorrow and post it here. Maybe it can be a good use for someone.

Thanks

Cem

Sent from my iPhone

On 26 Oct 2011, at 07:21 PM, "Sean Holden" <Sean.Holden at framestore.com<mailto:Sean.Holden at framestore.com>> wrote:

Tom has supplied a function called getname

He did this with:

getname()
{
bunch of code
}

You can then call the function in the script using its name 'getname'

He could have just as easily called it football

football()
{
bunch of code
}

and then use 'football' to call this code

Personally I use the following syntax:

function getname {

bunch of code

}

----------------------------------------

If you need to write a function you need to define it first and then call it when you like. So you could have something like the following. You can specify variables before or after the definition and then just call the function by its name to run it.

#!/bin/bash

outputBlurb=/tmp/rubbish

function spewrubbish {

echo $myBlurb > $myPath

}

myBlurb=wibble
myPath=$outputBlurb

spewrubbish

Hope that makes sense now.

Sean

Cem
Valued Contributor

I did look at jamfHelper, but no luck.

/Library/Application
Support/JAMF/bin/jamfHelper.apontents/MacOS/jamfHelper -help

JAMF Helper Help Page

Usage: jamfHelper -windowType [-windowPostion] [-title] [-heading]
[-description] [-icon] [-button1] [-button2] [-defualtButton]
[-cancelButton] [-showDelayOptions] [-alignDescription] [-alignHeading]
[-alignCountdown] [-timeout] [-countdown] [-iconSize] [-lockHUD]

-windowType [hud | utility | fs] hud: creates an Apple "Heads Up Display" style window utility: creates an Apple "Utility" style window fs: creates a full screen window the restricts all user input WARNING: Remote access must be used to unlock machines in this mode

-windowPosition [ul | ll | ur | lr] Positions window in the upper right, upper left, lower right or lower
left of the user's screen If no input is given, the window defaults to the center of the screen

-title "string" Sets the window's title to the specified string

-heading "string" Sets the heading of the window to the specified string

-description "string" Sets the main contents of the window to the specified string

-icon path Sets the windows image filed to the image located at the specified path

-button1 "string" Creates a button with the specified label

-button2 "string" Creates a second button with the specified label

-defaultButton [1 | 2] Sets the defualt button of the window to the specified button. The
Default Button will respond to "return"

-cancelButton [1 | 2] Sets the cancel button of the window to the specified button. The Cancel
Button will respond to "escape"

-showDelayOptions "int, int, int,..." Enables the "Delay Options Mode". The window will display a dropdown with
the values passed through the string

-alignDescription [right | left | centered | justified | natural] Aligns the description to the specified alignment

-alignHeading [right | left | centered | justified | natural] Aligns the heading to the specified alignment

-alignCountdown [right | left | centered | justified | natural] Aligns the countdown to the specified alignment

-timeout int Causes the window to timeout after the specified amount of seconds Note: The timeout will cause the the defualt button, button 1 or button 2
to be selected (in that order)

-countdown Displays a string notifying the user when the window will time out

-iconSize pixels Changes the image frame to the specified pixel size

-lockHUD Removes the ability to exit the HUD by selecting the close button

Return Values: The JAMF Helper will print the following return values to
stdout... 0 - Button 1 was clicked 1 - The Jamf Helper was unable to launch 2 - Button 2 was clicked XX1 - Button 1 was clicked with a value of XX seconds selected in the
drop-down XX2 - Button 2 was clicked with a value of XX seconds selected in the
drop-down 239 - The exit button was clicked 240 - The "ProductVersion" in sw_vers did not return 10.4.X, 10.5.X, or
10.6.X 243 - The window timed-out with no buttons on the screen 250 - Bad "-windowType" 254 - Cancel button was select with delay option present 255 - No "-windowType"

Bukira
Contributor

What about writing a GUI app in Xcode?

Criss Myers

Cem
Valued Contributor

I love to. But I don't know where to start :)
Can you recommend any sites?

Cheers
Cem

Jak
New Contributor III

This should do it:

getname() {
asmsg=`arch -i386 /usr/bin/osascript << EOT tell app "System Events" Activate set foo to text returned of (display dialog "Enter the name of the
Computer" buttons {"OK"} default answer "mr flibble") end tell
EOT`
if [ "$asmsg" = "false" ]; then getname else echo $asmsg
fi }

Call this like this

computername=getname

tlarkin
Honored Contributor

You could do something like this: (not tested)

#!/bin/bash

#set variables for computer name on local computer via post image script # this example assume cname is the variable used

#source the file that holds the computer name source /path/to/computernamefile

/usr/bin/osascript >>EndOfApplescript tell application "System Events" display dialog "Do you want to set the computer name to ${cname[@]} ?" { "Cancel" , "OK" } default button 2 if result = {button returned:"OK"} then do shell script "/usr/sbin/networksetup -setcomputername ${cname[@]}" else display dialog "Please see tech support to get the proper name changed." end if end tell EndOfApplescript

exit 0

No clue if this works I just whipped it up as proof of concept, I am not the strongest apple scripter out there, but this works with my previous solution on caching the name and it doesn't allow manual data entry which also has a margin of error.

-Tom

tlarkin
Honored Contributor

and I already noticed I have a syntax error

it should be

osascript <<EndOfApplescript

Cem
Valued Contributor

What is getname command?
Do you mean networksetup -getcomputername ?

Cem
Valued Contributor

Tom,

I am trying to get the staff to update the cname file or set the hostname with the pop up window.

Your script is asking; do you want to use cname to set up the hostname. So it assumes its all setup already.

Also it has some typo I think as it didn’t brought up the dialogue box.

Thanks for trying to help though.

Cheers

Cem

tlarkin
Honored Contributor

It is the function Mr. Piper wrote

Jak
New Contributor III

This is using bash functions.

You define the function

Myfunction()
{

Some code

}

You can then call this function in your script like any other command.

Thus

Foo='myfunction' <--- they are supposed to be back ticks, can't find on my iPhone.

You don't need to have it as a function, just the way I like to code.

Remove the getname and the {} and $asmsg will be the result from the dialog box

Hope that helps :)

Jak
New Contributor III

Mr Piper is my father :)

I'm Jak

On 26 Oct 2011, at 19:01, "Thomas Larkin" <tlarki at kckps.org<mailto:tlarki at kckps.org>> wrote:

It is the function Mr. Piper wrote

sean
Valued Contributor

Tom has supplied a function called getname

He did this with:

getname() { bunch of code }

You can then call the function in the script using its name 'getname'

He could have just as easily called it football

football() { bunch of code }

and then use 'football' to call this code

Personally I use the following syntax:

function getname {

bunch of code

}

----------------------------------------

If you need to write a function you need to define it first and then call it when you like. So you could have something like the following. You can specify variables before or after the definition and then just call the function by its name to run it.

#!/bin/bash

outputBlurb=/tmp/rubbish

function spewrubbish {

echo $myBlurb > $myPath

}

myBlurb=wibble myPath=$outputBlurb

spewrubbish

Hope that makes sense now.

Sean

tlarkin
Honored Contributor

It was Jak, not me...

I should probably brush up on my Apple script, but I am not really fond of user interaction with policy.

-Tom

Cem
Valued Contributor

Here is the script to change the name with ease in Casper Self Service (MCX applied to disabled Sharing prefs Naming). Thanks guys for all the help with osascript.
I have tested both scripts successfully in my environment. I suggest test it before using in your environment.

--missing content--

anges their Mac names)

  1. First script will remove the Mac from AD (set as before in policy)

#!/bin/sh
# This script will remove existing Directory records and will reset Search Paths
# to /Active Directory/mycompany.com
# Tested with 10.6.x
# Remove all files containing AD bindings informations

#####################################
#Clock restart / Remove existing settings
#####################################

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

CheckForNetwork

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

echo =93Starting network time synchronization=94

# Synchronize our clock to the network=92s 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
}

# Remove exisiting
logger =93Removing existing DS Config=94

if [ ! -d "/Library/Preferences/DirectoryService/ActiveDirectory" ]; then
rm -R /Library/Preferences/DirectoryService/ActiveDirectory*
fi

if [ ! -d "/Library/Preferences/DirectoryService/DSLDAPv3PlugInConfig" ]; t
hen
rm -R /Library/Preferences/DirectoryService/DSLDAPv3PlugInConfig*
fi

if [ ! -d "/Library/Preferences/DirectoryService/SearchNode" ]; then
rm -R /Library/Preferences/DirectoryService/SearchNode*
fi

if [ ! -d "/Library/Preferences/DirectoryService/ContactsNode" ]; then
rm -R /Library/Preferences/DirectoryService/ContactsNode*
fi

if [ ! -d "/Library/Preferences/edu.mit.Kerberos" ]; then
rm -R /Library/Preferences/edu.mit.Kerberos
fi

# Restart DirectoryService (necessary to reload AD plugin activation settin
gs)
killall DirectoryService
/bin/sleep 3

exit 0

  1. Second Script will rename the Mac and the record .txt file. (set as "bef ore" and make sure it runs after the first script above - alternatively you can combined them)

#!/bin/bash

# Lets enter the computername with GUI
getname()
{
asmsg`arch -i386 /usr/bin/osascript << EOT
tell app "System Events"
Activate
set foo to text returned of (display dialog "Enter the new name of the Comp
uter" buttons {"OK"} default answer "Type Computer Name Here")
end tell
EOT`
if [ "$asmsg" "false" ]; then
getname
else
echo $asmsg
fi
}
computernamegetname

# Set the computername
networksetup -setcomputername ${computername}

# This will update the original hostname record and it will keep the old re
cord with date stamp then set the permissions
mv /Library/Receipts/cname.txt /Library/Receipts/oldcname_`date +%M-%H-%m-%
d-%y`.txt
networksetup -getcomputername > /Library/Receipts/cname.txt
chmod -R 644 /Library/Receipts/cname.txt
chown -R root:wheel /Library/Receipts/cname.txt

# lets set the computer
setNamecat /Library/Receipts/cname.txt
scutil --set ComputerName ${setName}
scutil --set LocalHostName ${setName}

# Run Recon to update JSS record with the new name
jamf recon

exit 0 ## computermame and the record updated successfully
exit 1 ## fail

  1. Then check bind to AD in Account section of the Policy to bind the Mac t o AD. I have some editing Macs here that they don=92t need to be on domain. So I have set a pop up window message saying " Please run "AD bind" from S elf Service to join this Mac to domain. Then Restart or Shut Down."

I hope this is useful=85

Cem

Cem
Valued Contributor

I have now decided to add cancel button. It appears in GUI but doesn’t quit the script.
Is there way to cancel button to stop the entire process?

#!/bin/bash

# Lets enter the computername with GUI
getname()
{
asmsg=`arch -i386 /usr/bin/osascript << EOT
tell app "System Events"
Activate
set foo to text returned of (display dialog "Enter the new name of the Computer" buttons {"Cancel", "OK"} default button 2 default answer "Type Computer Name Here")
end tell
EOT`
if [ "$asmsg" = "false" ]; then
getname
else
echo $asmsg
fi
}
computername=getname

Jak
New Contributor III

Yup, the text returned when you hit cancel will be 'Cancel'

You can add another if statement or an elif, the value will be 'Cancel' so
If you read that back you can then exit 0

bentoms
Release Candidate Programs Tester

If that's not working.... I've a script somewhere that deletes the UTC database & uses AppleScript to prompt & can be ran from remote (with or without prompts) or self service.

I can dig it up if it helps.

Regards,

Ben.