How To: Get the currently logged in user, in a more Apple approved way

Standard

When running scripts via the JSS, you sometimes have a challenge to get the username of the currently logged in user.

If you’re running the script at login or via Self Service, then $3 can be used to grab the username. However, you’ll quickly find that at times you’ll want to find the username whilst running a policy at another time than at login or via Self Service.

A common method used is below & you’ll find it in a number of my scripts.

This has served me well, but the method has issues when multiple users are logged in with Fast User Switching enabled. As it will return the username for all Users.

On seeing an example of the above, Frogor over at the ##OSX-Server IRC mentioned that this method was both a little “odd” & not Apple’s recommended way. Then, being the guy he is.. He not only pointed us in IRC to a link about Apple’s recommended method, but also gave an example of how to call it within bash. That example is below:

You’ll start to see the above soon in my new posts, & if you do use Fast User Switching then this may work better for you where other methods have failed.

17 thoughts on “How To: Get the currently logged in user, in a more Apple approved way

    • Whilst that works, it’s only as good as your last recon & depends on when that is.

      The above can be run as part of a script whenever.

  1. jaknz

    Best Practice is also to use $(do stuff here) instead of `do stuff here`. If that got reformatted, replace the back-ticks surrounding the python code with a dollar+open parenthesis and end the block with a close parenthesis.

  2. James Brickley

    Make sure specify /usr/bin/python:
    `/usr/bin/python -c ‘from SystemConfiguration…

    Specify the full path to python or it might use a /usr/local/bin/python and not load the modules that Apple provides with their customized python.

  3. What’s odd is the Technical Q&A link states:

    – It has no way of indicating that multiple users are logged in.

    – It has no way of indicating that a user is logged in but has switched to the login window.

    Perhaps I’m misunderstanding?

    • Forgot to add the line from the Q&A: “Because of these issues, routines like SCDynamicStoreCopyConsoleUser exist only for compatibility purposes. It’s likely that they will be formally deprecated in a future version of Mac OS X.”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.