Skip to content

Instantly share code, notes, and snippets.

@pmbuko
Last active August 29, 2015 14:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmbuko/445c56e5d63ec332eb98 to your computer and use it in GitHub Desktop.
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 a dot-separated version
# of the full name of the most-commonly-logged-in user with a local home.
# Give a list of usernames to ignore, separated by spaces
ignore_list=( root admin administrator bukowinskip )
# Get a list of usernames sorted by login frequency, limited to the last 100 logins
login_list=$(last -t console -100 | \
awk '/console/{print $1}' | \
sort | uniq -c | sort -r | awk '{print $2}')
# Simple function to check if user is in ignore list
ignore_match () {
local i
for i in "${ignore_list[@]}"; do [[ "$i" == "$1" ]] && return 0; done
return 1
}
# 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 if user is not in ignore_list and has a local home
if ! ignore_match "$u" && [ -d "/Users/${u}" ]; then
# Get user's full name, substituting periods for spaces
dotted_name=$(dscl -plist . read "/Users/$u" RealName | \
awk 'BEGIN { OFS="." } /string/{gsub("<.?string>","");$1 = $1;print}')
# Set the hostnames (comment echo lines and uncomment scutil lines after testing)
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