Getting the current user in macOS – Update

I recently posted an article on how to get the current user in macOS. If you read through that entire post, it’ll be obvious that it was actually an excuse to write about the deprecation of python 2 and /bin/bash and the situation with sh ‘compatible’ code.

The ‘tl;dr’ of that post was to stop using the python one-liner and use this scutil based one-liner, based on Erik Berglund’s post, instead.

zsh and bash scripts

loggedInUser=$( scutil <<< "show State:/Users/ConsoleUser" | awk '/Name :/ && ! /loginwindow/ { print $3 }' )

sh scripts

loggedInUser=$( echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ && ! /loginwindow/ { print $3 }' )

From now on, I will call these the ‘SystemConfiguration’ solution (this also includes the python one-liner). Both the python and the scutil based one-liners go through the SystemConfiguration framework to get at the desired information: which user is using the ‘Console?’

The ‘console’ in this case is an abstract definition, which encompasses the screen output and most inputs. I could not find a clear definition of what the ‘Console’ is exactly on macOS. (If you can point me to one, I’d be grateful.) But it serves to think of the console as all the processes, inputs and outputs attached to a user’s login session.

The other one-liner

There is another solution that keeps popping up in MacAdmins Slack and blog posts.

loggedInUser=$(stat -f %Su /dev/console)

(The stat solution.) This certainly looks much shorter and simpler. But does it return the same in all situations? Is it actually the same?

Testing the Edge

I have done some testing with Fast User Switching and a second remote Screen Sharing session. These are the weird edge cases for which the original python one-liner was devised.

I had a remote ssh session open from my main Mac while I logged two test users in and out of a second test Mac. I ran the commands for the SystemConfiguration and stat solutions in the ssh session, and compared the return values.

In (nearly) all multiple user sessions combinations that I tested, both the SystemConfiguration and the stat solution return the same value.

It is worth pointing out, that when you have two users with graphical sessions at the same time, neither of the two solutions will actually return the “currently” active user session, but the user owning the sessions that was last logged in to. This is especially relevant when someone use Screen Sharing to create a remote graphical session on an Mac. In this case both methods will return the last user that logged in, even though both users currently have active sessions.

How the stat solution works

The stat command shows the user owning the /dev/console file. When we look at that ‘file’ with the ls command:

> ls -al /dev/console  
crw-------  1 armin  staff    /dev/console

We get a file type (the first character of the listing) of ‘c’ which represents a ‘character special file.’ All the ‘files’ in /dev are of this file type. When you look closely you will ‘files’ in here representing the disks connected to your Mac (disk*), the Bluetooth devices (cu.*), and some other weird ‘files.’

This stems back to the Unix underpinnings of macOS where everything has a representation in the file system hierarchy, whether it is actual data on a disk or not. The ‘files’ we are seeing here are an abstraction of devices and other objects in the system.

With that background in mind, it should be clear that we are looking at the same data from the system, abstracted in different ways. Either through the SystemConfiguration framework or the Unix file system. So, we get the same data either way, right?

The difference at login window

Not quite. I found one difference. When the Mac is at the login window, the SystemConfiguration solution returns an empty string and the stat solution returns root.

This is not the entire truth, though. When you look closely at the SystemConfiguration solution, you will that there is a clause, in both the python and scutil versions, that catches a return value of loginwindow and returns and empty string instead.

When you look at the raw output of the scutil command used, we actually get quite a lot of information:

> scutil <<< "show State:/Users/ConsoleUser"
<dictionary> {
  GID : 20
  Name : armin
  SessionInfo : <array> {
    0 : <dictionary> {
      kCGSSessionAuditIDKey : 100009
      kCGSSessionGroupIDKey : 20
      kCGSSessionIDKey : 257
      kCGSSessionLoginwindowSafeLogin : FALSE
      kCGSSessionOnConsoleKey : TRUE
      kCGSSessionSystemSafeBoot : FALSE
      kCGSSessionUserIDKey : 501
      kCGSSessionUserNameKey : armin
      kCGSessionLoginDoneKey : TRUE
      kCGSessionLongUserNameKey : Armin Briegel
      kSCSecuritySessionID : 100009
    }
  }
  UID : 501
}

The awk statement after the scutil command filters out the information we need:

awk '/Name :/ && ! /loginwindow/ { print $3 }' 

This will return lines containing Name : and not containing loginwindow. In other words, if the scutil command returns loginwindow in the line, the entire scutil ... | awk ... construct will return nothing or an empty string.

When you leave out the extra awk clause to filter the loginwindow return value, you will get loginwindow while the login window is shown:

scutil <<< "show State:/Users/ConsoleUser" | awk '/Name :/  { print $3 }'

The edge of the edge case

So, the SystemConfiguration solution returns loginwindow or nothing when the Mac is sitting at a login window and the stat solution returns root. Not a big deal right? I just have to consider this difference when I test whether a user is logged in?

I found one edge case (to the edge case) where this difference matters: the stat solution will return root when at the login window and when the root account or System Administrator is logged in.

Now, enabling the root account and logging in and working as root is most definitely not recommended on macOS. So, there is an argument that this edge case should not occur.

But users have a way of ignoring these kind of recommendations. The SystemConfiguration solution will allow your scripts to actually distinguish between a Mac sitting at the login window and the (admittedly rare but extremely dangerous) situation where a user is logged in as root.

Conclusions

So, in most cases the stat solution is identical to the SystemConfiguration solution. It has the advantage of being shorter and easier to read.

When you anticipate that you might need to distinguish between the computer being at the login window and a root user being logged in, or when you are just paranoid about catching all edge cases, the SystemConfiguration solution is more complete.

If in doubt, use the SystemConfiguration solution.

Weekly News Summary for Admins — 2020-01-31

Update week! macOS Catalina 10.15.3 and the iOS 13.3.1 and other related updates dropped. And while the Catalina update seems to fix some things it also breaks others. Thanks to the all the contributors for the extra information that Apple does not provide.

If you would rather get the weekly newsletter by email, you can subscribe to the Scripting OS X Weekly Newsletter here!! (Same content, delivered to your Inbox once a week.)

📰News and Opinion

🐦MacAdmins on Twitter

  • Sarah: “Well, it’s racked. Looks kind of funny next to an Xserve though. https://t.co/BnKwR499VI” (Images)
  • Rosyna Keller: “Don’t use PackageMaker to make installer packages. It’s a long dead tool (2012 or so) and developers should switch to productbuild/pkgbuild*, which incorporate the command line utilization. It also can’t create signed packages. *Or is a third-party toool that scripts these. Installer packages are required to be signed to be notarized (so PackageMaker packages are out) and, as PackageMaker was a 32-bit app, it won’t run on Catalina. It’s that old.”

🔨Support and HowTos

🤖Scripting and Automation

🍏Apple Support

🏝macOS Catalina 10.15.3 and iOS 13.3.1

♻️Updates and Releases

🎧To Listen

🎈Just for Fun

📚 Support

There are no ads on my webpage or this newsletter. If you are enjoying what you are reading here, please spread the word and recommend it to another Mac Admin!

If you want to support me and this website even further, then consider buying one (or all) of my books. It’s like a subscription fee, but you also get a useful book or two extra!

Weekly News Summary for Admins — 2020-01-24

We got the third group beta releases for the next updates this week. Can I just gripe for a moment that macOS 10.15.2 was released along side iOS 13.3 and watchOS 6.1.1, while 10.15.3 will (probably) be released along side iOS 13.3.1 and watchOS 6.1.2? Apple versioning makes no sense at all, any more.

If you would rather get the weekly newsletter by email, you can subscribe to the Scripting OS X Weekly Newsletter here!! (Same content, delivered to your Inbox once a week.)

News and Opinion

MacAdmins on Twitter

  • Tim Perfitt: “Reboot to recovery on next reboot: sudo nvram "recovery-boot-mode=unused" Subsequent reboots go back to macOS.”
  • Roben Kleene: “Some of the built-in scripting language binaries (only the interactive ones?) now print a warning message about not being included by default in a future version of macOS. Just in case you were wondering how serious they are about this: They’re serious.”
  • Jeff Johnson: “I’ve learned that Apple engineers have internal tools which allow them to delete macl xattr as well as to bypass other Catalina privacy and sandbox protections without rebooting and disabling SIP. Inside Apple they don’t suffer the same problems as external users and developers.”

Support and HowTos

Scripting and Automation

Updates and Releases

To Listen

Just for Fun

  • Jenny on Twitter: “No one asked for this. But here it is: every macOS wallpaper from Mac OS X 10.0 Cheetah to macOS 10.15 Catalina combined.” (Follow link for image)

Support

There are no ads on my webpage or this newsletter. If you are enjoying what you are reading here, please spread the word and recommend it to another Mac Admin!

If you want to support me and this website even further, then consider buying one (or all) of my books. It’s like a subscription fee, but you also get a useful book or two extra!

Weekly News Summary for Admins — 2020-01-17

Somewhat slow week for MacAdmin news. The new year is still ramping up.

If you would rather get the weekly newsletter by email, you can subscribe to the Scripting OS X Weekly Newsletter here!! (Same content, delivered to your Inbox once a week.)

On Scripting OS X

News and Opinion

On Twitter

  • Steve Hayman: “Happy 40th Birthday to one of my favourite Unix features, the Shebang! Dennis Ritchie introduced the two-character #! sequence – which tells Unix how to execute a script file – 40 years ago today.”
  • Carl Ashley: “Interrogating a preinstall script for a package. It’s doing naughty things. This is just a sample. What package sins keep you awake at night, macadmins?… ” (Image)

Bugs and Security

Support and HowTos

Scripting and Automation

To Listen

Updates and Releases

Support

There are no ads on my webpage or this newsletter. If you are enjoying what you are reading here, please spread the word and recommend it to another Mac Admin!

If you want to support me and this website even further, then consider buying one (or all) of my books. It’s like a subscription fee, but you also get a useful book or two extra!

Weekly News Summary for Admins — 2020-01-10

Happy New Year!

New decade, even. Well, the last decade has certainly been… interesting.

What ever the new year (and decade) brings from the Apple Admin side of things, I will link to it!

I will be presenting at MacAD.UK (March 24–25) this year again. The topic of my session will be “Terminal Wizardry and and Witchcraft 2020” which will pick up on the presentation from two years ago. Much has changed since then and it is time for an update. I am looking forward to meeting you there!

Quite a bunch of links this time, because we were off for two weeks and this is the catch up summary. You can tell that most MacAdmins were able to take some time off as well, except for Howard Oakley (Eclectic Light) who just kept publishing like he always does. (Thank you for all your work, Howard!)

If you would rather get the weekly newsletter by email, you can subscribe to the Scripting OS X Weekly Newsletter here!! (Same content, delivered to your Inbox once a week.)

Headlines

“Apple Device Management: A Unified Theory of Managing Macs, iPads, iPhones, and AppleTVs” by Rich Trouton and Charles Edge

On Scripting OS X

News and Opinion

MacAdmins on Twitter

  • Fiora: “looks like dropbox doesn’t like me using dropbox as an automatic backup service… ” (Thread)
  • Jason Broccardo: “It’s 2020 and you know what that means, right? Adobe Flash Player dies at the end of this year!”
  • Roy van Rijn: “One of our office chairs turns off monitors… we couldn’t believe it, but we have it on tape. Surprisingly, there even is a known issue for it”

Bugs and Security

Support and HowTos

Scripting and Automation

Apple Support

Updates and Releases

To Listen

Just for Fun

Support

There are no ads on my webpage or this newsletter. If you are enjoying what you are reading here, please spread the word and recommend it to another Mac Admin!

If you want to support me and this website even further, then consider buying one (or all) of my books. It’s like a subscription fee, but you also get a useful book or two extra!

Command-Control-Power Podcast featuring Scripting OS X!

I have the honor of being a guest on the latest Command-Control-Power podcast!

The wonderfully gracious hosts Joe Saponare and Sam Valencia talk with me about life as admin/consultant, my new book “Moving to zsh,” what the new shell means for Mac users and also the EraseInstall app we built at ProWarehouse and how workflows are important for admins and consultants.

I had a great time while we were recording this podcast, even though we had to schedule it “way past my usual bedtime.” I hope you enjoy listening, as well!

Book Update – Moving to zsh v3

I have pushed an update for the “Moving to zsh” book.

Just a few changes and fixes that have accumulated over the past two weeks. Much of this has been from feedback of readers. Thanks to everyone who sent in their notes.

The update is free if you have already purchased the book. You should get a notification from the Books application to update. (On macOS, I have seen that it can help to delete the local download of the book to force the update.)

If you are enjoying the book, please rate it on the Books store, or (even better) leave a review. These really help, thank you!

Also, please recommend the book to friends, co-workers, and anyone else (not just MacAdmins) who might be facing the zsh transition as they upgrade to Catalina.

The changes in v3 are listed here. This list is also in the ‘Version History’ section in the book. There, you will get links to the relevant section of the book, so you can find the changes quickly.

  • Added a section explaining how to work with upper- or lower-case strings in zsh scripts
  • Added a section explaining the differences in the read built-in command
  • Clarified the section on Connected Variables
  • Fixed file names in the table for Configuration Files and added a note for how to use configuration files with python environments
  • As usual, several typos and clarifications (Thanks to many readers)

Downgrading a Mac that shipped with Catalina to Mojave

Apple has started shipping Mac models that used to come with Mojave pre-installed with Catalina. If your organization has blockers for Catalina (incompatible software, etc.) you may want to install Mojave on these Macs. Unfortunately, this is not so easy.

Important Notice: these instructions will only work for Mac models that can boot to Mojave. Usually a Mac requires at least the version of macOS that the model shipped with when it was introduced. As of this writing, all new Macs require at least Mojave. The exceptions are the iMac Pro (High Sierra) and the MacBook Pro 16“ and the Mac Pro (2019) which both require Catalina. You cannot use these instructions to force a Mac Pro or MacBook Pro 16” to boot to Mojave. Any new Mac models that Apple introduces from now on, will also require Catalina and cannot be downgraded to Mojave.

(Not meant as a challenge. I am aware that someone might be able to hack together a Chimera Mojave with Catalina drivers. These ‘solutions’ are not supportable on scale.)

Directly downgrading from Catalina to Mojave with the startosinstall --eraseinstall command will fail. Attempts to run the Mojave installer from a Catalina Recovery (local or Internet) will also fail. The reason seems to be that the Mojave Installer application chokes on some aspect of Catalina APFS. Apple is likely not very motivated to fix this.

So far, the recommendation has been to boot to Internet Recovery with the shift-command-R key combination at boot. This used to boot to a Mojave (more specfically, the system the Mac shipped with) recovery system, and then you can wipe and re-install Mojave. However, if a Mac was shipped with Catalina pre-installed, it will boot to Catalina Internet Recovery, regardless of whether the Mac can boot to Mojave or not.

We have to get creative.

External USB Installer

The solution requires a Mojave Installer USB disk. First download the latest Mojave installer. You can do so from by following this App Store link. If you are running Catalina, you can also use the new option in softwareupdate:

> softwareupdate --fetch-full-installer --full-installer-version 10.14.6


Then you can use the createinstallmedia command in the Install macOS application to build an external Installer Drive on a USB drive. You probably want to add the --downloadassets option to add the current firmware to the USB drive as well.

> createinstallmedia --volume /Volumes/Untitled --downloadassets


This will delete the target volume data on the USB disk.

Enable External Boot

To boot a new Mac with a T2 chip off an external drive, you need to allow external boot from the Security Utility in the Recovery partition. This utility is protected and requires the password of a local administrator user to access. When you get a new Mac “out of the box,” you cannot directly boot to Recovery to change this.

Instead, you have to boot to the pre-installed Catalina, work your way through the Setup Assistant, and create a local administrator user before you can boot to Recovery to change this setting.

You also need to connect the Mac to a network with non-filtered/proxied access to Apple’s servers, either with Wifi or an ethernet adaptor. You can see which services and servers the network needs to be able to access in this kbase article. You will definitely need the servers listed under ‘Device Setup’ from that list and many of the others, depending on your deployment workflow.

This network connection is required to verify the integrity of the system on the USB Installer drive. You could also disable ‘Secure Boot’ entirely, but that is not recommended as it will, well, disable all system security verifications.

Now, reboot the Mac and hold the option key, from the list of devices to boot from, select the Mojave Installer drive. Once booted to the Mojave installation drive, start Disk Utility. In Disk Utility, erase the entire internal drive. You may have to choose ‘Show All Devices’ from the View menu to be able to select the internal drive with all sub volumes, not just the system or data volume.

Then you can quit Disk Utility and start the Mojave installation process.

After completing the installation, you want to remember to return to Recovery and re-disable external boot again. However, you need to create a new admin account on the disk before you can do that…

Avoiding the Downgrade

This is obviously tedious and really hard to automate. (I have been wondering if you could build a MDS workflow, but this one would require at least three reboots.)

The preferred solution is for IT departments and organizations to have the workflows and infrastructure in place to support and use “latest macOS” (Catalina). Apple is discouraging system downgrades or using anything but “latest macOS.” On newer hardware — like the MacBook Pro 16″, Mac Pro 2019, and every new Mac Apple will introduce from now on — downgrading to Mojave is not possible at all, so you have to support Catalina when you (or your users) get those Mac models.

As mentioned before, I do not believe there is much motivation at Apple to simplify this particular workflow. It serves Apple’s interest and vision to push the latest macOS over previous versions. From a user perspective it allows better integration with their iOS and other Apple devices. From a security standpoint it provides the latest security updates and patches. Apple provides security updates for the previous two macOS versions, but those notoriously do not fix all the vulnerability that the latest macOS gets.

However, in some cases you may have blocking applications that cannot run, or cannot be upgraded to run on Catalina. Then this workflow can be a ‘last ditch’ solution until you get those ‘blockers’ sorted out.

Maybe the best solution is to use this complex and work intensive downgrade workflow as leverage to push for “latest macOS” support in your organization.

Thanks to Robin Lauren and Mike Lynn for figuring this out on MacAdmins Slack and sharing their results.

Weekly News Summary for Admins — 2019-12-20

We are close to completing another trip around the sun. Whether you use the solstice (Dec 22) or the Perihelion (Jan 5) or the quaint Gregorian Calendar which switches on Dec 31.

(Dates are for UTC. The exact astronomical event may be it may be a Dec 4 or Jan 4 at your location, depending on your time zone.)

You’d think that Apple would take an early break after the Mac Pro release, but we got new and updated security documentation. Together with the new deployment and MDM documentation updated last week.

Because of the holidays, this newsletter will be taking a break as well. The next one should be on Jan 10, 2020, summarizing everything that happened in the mean time.

I wish you Happy Holidays and all the best for the new Year 2020!

See you next year!

Armin Briegel

Note: if you get an AppStore/iTunes Gift Card for Christmas, gift yourself one of my books!

If you would rather get the weekly newsletter by email, you can subscribe to the Scripting OS X Weekly Newsletter here!! (Same content, delivered to your Inbox once a week.)

Headlines

This is a good summary, but I find the continued expectation that Apple has to keep delivering “Blockbuster” devices quite tiresome. Who else is has delivered blockbuster devices? Also, the statement implies that the iPad, Apple Watch, and AirPods (all introduced since 2010) aren’t blockbusters?

macOS Support Essentials 10.15 – Apple Pro Training Series: Supporting and Troubleshooting macOS Catalina – Adam Karneboge and Arek Dreyer – Available for PreOrder!

On Scripting OS X

News and Opinion

MacAdmins on Twitter

  • Jean-David Gadina: “You can keep SIP but allow debugging (including instruments) with csrutil enable --without debug --without dtrace”
  • Russ Bishop: “TIL: 3rd party kext tries to inject macOS dylib into all processes, breaks downloaded simulators. Surprise! Simulator binaries can’t load mac dylibs. So far that’s four unique ways I’ve seen badly made kernel extensions break simulators. All are ”security“ products.”

Bugs and Security

Support and HowTos

Scripting and Automation

Apple Support

This joins last week’s new documentation:

Updates and Releases

To Listen

Just for Fun

Support

There are no ads on my webpage or this newsletter. If you are enjoying what you are reading here, please spread the word and recommend it to another Mac Admin!

If you want to support me and this website even further, then consider buying one (or all) of my books. It’s like a subscription fee, but you also get a useful book or two extra!