Skip to content

Instantly share code, notes, and snippets.

@pmbuko
Last active August 29, 2015 14:27
Show Gist options
  • Select an option

  • Save pmbuko/445c56e5d63ec332eb98 to your computer and use it in GitHub Desktop.

Select an option

Save pmbuko/445c56e5d63ec332eb98 to your computer and use it in GitHub Desktop.
This script will change the hostname of a Mac to a dot-separated version of the full name of the most-commonly-logged-in user with a local home found under /Users.
#!/bin/bash
# This script will change the hostname of a Mac to the full name of the
# most-commonly-logged-in user with a local home found under /Users.
# Get a list of usernames sorted by login frequency, limited to the last 100 logins
login_list=$(last -t console -100 | \
awk '/console/ && !/root/{print $1}' | \
sort | uniq -c | sort -r | awk '{print $2}')
# This block will run through login_list and operate on only the first username in the list
# that happens to have a local home.
for u in $login_list; do
# Proceed only if the user has a local home in the expected location
if [ -d "/Users/${u}" ]; then
dotted_name=$(dscl . read "/Users/$u" RealName | awk 'BEGIN { OFS="." } !/:/{$1 = $1;print}')
# Now set the hostnames
echo "This script would have changed the compter name to '$dotted_name'"
echo "Uncomment the three 'scutil' lines in the script to make it actually change it."
#scutil --set ComputerName $dotted_name
#scutil --set LocalHostName $dotted_name
#scutil --set HostName $dotted_name
# skip all further names in login_list
break
fi
done
@gregneagle
Copy link

If I were to use some variation of this, I'd probably also have a "ignore list" of account names to ignore, with the primary (or maybe only) member being our local admin account.

When a machine is first deployed it's not unheard of for the local admin account to be a more "frequent" user than the (new) local user.

@pmbuko
Copy link
Author

pmbuko commented Aug 13, 2015

That's a good point, Greg. I modified it to include that functionality.

@rmanly
Copy link

rmanly commented Aug 13, 2015

I was racking my brain at lunch trying to remember where this was and I just now remembered…and then I facepalmed when I read Greg's second sentence here.

But, since I had a eureka moment "It was in Tim's repo!" I am posting it anyway 😛

getMostFrequentUser
ac -p | sort -nrk 2 | awk 'NR == 2 { print $1; exit }'

timsutton/scripts@3769764

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment