Get two-factor authentication code from terminal

bashterminaltwo-factor-authentication

Is it possible to retrieve my Apple ID two-factor authentication code via the terminal instead of the GUI prompt, i.e. via ssh or a bash script?

I don't own any Apple devices other than a headless Mac mini for iOS development (I am loaning some iOS devices for development, but don't want to mark those as trusted, for obvious reasons).

Right now, I have to remote desktop into the Mac mini to get the 2FA code whenever I need it. I'd like to be able to at least just ssh, if not set up a bash script to text me when prompted.

Best Answer

I came up with a pretty simple solution to this problem using AppleScript that should print the 2FA code:

#! /usr/bin/env osascript tell application "System Events" if name of every process contains "FollowUpUI" then tell window 1 of process "FollowUpUI" click button "Allow" delay 2 set code to value of static text 1 of group 1 log (code) click button "Done" end tell else log ("Couldn't find 2FA window") end if end tell return

Adding this to a file and making it executable using chmod +x name_of_file.scpt should create a script that can be run over ssh by executing ./name_of_file.scpt while in the same directory as the file.

Note: When you run this script over ssh for the first time, the following popup should appear:

enter image description here

Simply clicking "OK" should allow the script to run properly. This preference will automatically be saved, and can be modified by going into System Preferences->Security & Privacy->Privacy->Accessibility

This worked for me on macOS Mojave, but it may work on other versions as well.