Skip to content

Instantly share code, notes, and snippets.

@rmanly
Created November 27, 2012 22:13
Show Gist options
  • Save rmanly/4157514 to your computer and use it in GitHub Desktop.
Save rmanly/4157514 to your computer and use it in GitHub Desktop.
returns DOMAIN\Username for user with the most time logged on
#!/bin/bash -
#===============================================================================
#
# FILE: recordname_for_greatest_user.bash
#
# USAGE: ./recordname_for_greatest_user.bash
#
# DESCRIPTION: returns DOMAIN\user for the network user with most time on system
# * with changes to dscl this no longer works in 10.8 and maybe 10.7
#
# AUTHOR: Ryan Manly (), ryan.manly@gmail.com
# COMPANY: Glenbrook High School District 225
# CREATED: 12/14/2011 18:04:40 CST
# REVISION: ---
#===============================================================================
i=0
userlist=()
# read a heredoc into an array using the output from the commmand by PBUKOWINSKI tweaked a bit
# reverse the sort and don't print the top line which is the total from ac
read -a userlist <<< $(ac -p | sort -nrk 2 | awk 'NR >= NF {print $1}')
# run dscl with the first index in the array [0] and redirect stdout to a temp file so we can get the line we want later
# redirect stderr so we don't see the message from dscl
# if dscl returns success then break out of the while true loop
# dscl and break are grouped with {} so that we can properly increment i if dscl errors
# this lets us try again with the next element in the array ${userlist[1]}
while true; do
{ dscl "/Active Directory/All Domains/" -read "/Users/${userlist[$i]}" RecordName > /tmp/output.txt 2> /dev/null && break; } || ((i++))
done
# get line 5 from output.txt, sub leading spaces, print, and exit because we don't need to operate on lines 6-NF
# line 5 of my output from dscl command above has the DOMAIN\username format d'Entremont was looking for
awk 'NR==5 { sub(/^[ ]+/, ""); print; exit }' < /tmp/output.txt
rm /tmp/output.txt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment