Pretty much every script I’m working on these days must be run as root. Checking what user is running something is pretty straight forward, as there’s a built-in shell variable for $USER that contains the user running a script. To see this real quick, simply run the following:
You can then put this into your scripts. I’ve been using the same block of code for decades, which can be run in a script by itself if you’d like to paste this into one.
if [[ $USER != "root" ]]; then
echo "This script must be run as root"
echo "You are root"
Note: Keep in mind that the built-in $USER variable is case sensitive.
Obviously, most people won’t keep the lines that contain the else and you are root echo statements. You can just remove these or replace them with the meat of your script that requires elevated privileges to run. Enjoy.
Previously, I covered how to Programmatically Obtain Recent Wi-Fi Networks On A Mac
. But, here I’m gonna’ go a step further and look at how to extract the password for a network as well. The two are stored in different locations. The recent networks are in the /Library/Preferences/SystemConfiguration/com.apple.airport.preferences defaults domain. If you pull one of those, then you can use the security command to extract the password itself.
security find-generic-password -ga "Krypted Home"
The output is as follows, showing everything that is tracked about this network in the keychain.
0x00000007 <blob>="Krypted Home"
"desc"<blob>="AirPort network password"
You can constrain the output with awk and grep so that you’d only see the password as the output of the command. Then, you can feed it back into other objects, like a new .mobileconfig.