Last edit: May 27, 2019 09:30:46 AM CDT
List of all cheatsheets
See also *nix and Bash
Applications
Which applications are from the App Store?
find /Applications -path '*Contents/_MASReceipt/receipt' -maxdepth 4 -print |\sed 's#.app/Contents/_MASReceipt/receipt#.app#g; s#/Applications/##'
Get application version information
mdls /path/to/app | awk '/kMDItemVersion/ {print $3}' | sed s/\"//g
defaults read /path/inside/appbundle/Contents/Info CFBundleShortVersionString
Get info on an Application binary
file /Applications/[app].app/Contents/MacOS/[app]
Get verbose information about an Application
mdls /Applications/[app]
Find all applications owned by admin user and reset to standard ownership
find /Applications -user ladmin -print0 | xargs -0 chown root:admin
Create a list of only the applications installed in /Applications
mdfind -onlyin /Applications "kMDItemKind == Application" | sort
Find all non-Apple applications installed in /Applications
mdfind -onlyin /Applications "kMDItemCFBundleIdentifier != com.apple.*"
Get an application's exact file path
mdfind kMDItemCFBundleIdentifier = "[BundleIdentifier]"
Install Xcode CLI Tools
xcode-select --install and then sudo xcode-select --reset
List application's linked frameworks & dylibs
otool -L /path/to/executable
List system files used by an executable
otool -L /path/to/executable
Launch with root access from any user account
sudo -u root /Applications/app.app/Contents/MacOS/app
Open an app in the background
/usr/bin/open -a /Applications/[app name] --hide
When was a running app launched?
lsappinfo info "[app name]" | awk '/launch time/ {print $4,$5}'
How long has an app been running?
lsappinfo info "[app name]" | awk '/launch time/ {print $7,$8,$9,$10}' | sed s/\,//g
Quick check to see if a particular app has likely been recently used
sudo sqlite3 /private/var/db/CoreDuet/Knowledge/knowledgeC.db -list 'select ZVALUESTRING from zobject where ZSTREAMNAME="/app/inFocus"' | grep [app name (case sensative)] | wc -l
Get a list of 32-bit apps that have been launched on a 10.14+ Mac
sqlite3 /var/db/SystemPolicyConfiguration/ExecPolicy 'select exec_path from legacy_exec_history_v4' | sort
Force Chrome to restart
osascript -e 'tell application "Google Chrome" to open location "chrome://restart"'
Packages, Installation & VPP
productbuild will build distribution packages
Package receipts live in /var/db/receipts
List of installed packages
pkgutil --pkgs
Get a list of installed applications
/usr/libexec/mdmclient QueryInstalledApps
When was an Apple package installed?
system_profiler SPInstallHistoryDataType | grep -A 2 -B 3 "Source: Apple"
Detailed list of when packages where installed
cat /Library/Receipts/InstallHistory.plist
What date was a package installed
pkgutil --pkg-info [package info from pkgutil --pkgs] | date -r $(awk '/install/ { print $2 }')| awk '{ print $2,$3,$6 }'
Get metadata for installed files
pkgutil --file-info /path/to/pkg
What files will be installed by a package
pkgutil --payload-files /path/to/pkg
What files where installed by a package
pkgutil --files [pkg]
Forget packages from install database
pkgutil --regexp --forget "com\.company\.product\.s*"
Create a list of all the files that will be installed by a package
for pkg in [path/to/pkg]; do pkgutil --payload-files $pkg >> /path/to/out.txt; done
Build a basic component package
pkgbuild --component /path/to/item/topackage --install-location /path/to/install/to [package name].pkg
Build a payload-free package
pkgbuild --nopayload -scripts /path/to/scripts_folder --identifier [com.company.packagename] —-version [version number] /destination/packageName.pkg
Build a basic package
pkgbuild --identifier [com.company.packagename] --root /path/to/files -—ownership preserve —-version [version number] packageName.pkg
Convert flat component package into a distribution package
productbuild --package /path/to/component.pkg /path/to/distribution.pkg
Check a DMG's signature (10.12+)
spctl -a -t open --context context:primary-signature -v MyImage.dmg
Which hardware is supported by OS installer
cat /System/Library/CoreServices/PlatformSupport.plist
Create a disk-based installer from macOS Installer.app
/Applications/Install\ [OS version].app/Contents/Resources/createinstallmedia --volume /Volumes/[target] --applicationpath [/path/to/Installer.app] --nointeraction
10.14+: --downloadassets will download on-demand assets that may be required for installation.
Get OS build version from Installer.app (10.13+)
cat Install\ macOS\ High\ Sierra.app/Contents/SharedSupport/InstallInfo.plist | awk '/10/'
Get OS build version from Installer.app (OSes prior to 10.13)
1. Mount InstallESD.dmg
2. hdiutil attach BaseSystem.dmg
3. defaults read /Volumes/OS\ X\ Base\ System/System/Library/CoreServices/SystemVersion.plist
startosinstall usage
/path/to/Install macOS High Sierra.app/Contents/Resources/startosinstall --nointeraction --volume /path/to/volumetoinstallon --applicationpath /path/to/installer
Install package with startosinstall
Packages must all be signed or unsigned distribution-style flat packages
Don't use spaces in package names
startosinstall --applicationpath /Applications/Install\ macOS\ High\ Sierra.app --agreetolicense --installpackage /path/to/package.pkg --installpackage /path/to/package_two.pkg --nointeraction
Setup a machine to use the beta software feed
/System/Library/PrivateFrameworks/Seeding.framework/Resources/seedutil enroll CustomerSeed | DeveloperSeed | PublicSeed
• CustomerSeed – AppleSeed betas
• DeveloperSeed – Apple Developer betass
• PublicSeed – macOS public beta
Which beta feed is a machine enrolled in
/System/Library/PrivateFrameworks/Seeding.framework/Resources/seedutil current
Remove a machine from the beta feed
defaults delete /Library/Preferences/com.apple.seeding
/System/Library/PrivateFrameworks/Seeding.framework/Resources/seedutil unenroll
Miminum OS that meets an application's system repquirements
defaults read /Applications/[app name]/Contents/Info LSMinimumSystemVersion
Read contents of a VPP token
base64 --decode /Path/To/domain.vpptoken
base64 -D /Path/To/domain.vpptoken | xxd
Package macports install into a standalone installer
sudo port pkg [app]
sudo port mpkg [app]
Choices XML
installer -package /path/to/pack.pkg -showChoicesXML
installer -pkg /path/to/package.pkg -applyChoiceChangesXML /path/to/file.xml -target [/]
“Changing the ‘visible’ and ‘enabled’ attributes only affects their display in
Installer.app; to control what is installed, we need to control the ‘selected’
choiceAttributes” — http://code.google.com/p/munki/wiki/ChoiceChangesXML
Defaults
10.8+ uses cfprefsd, which is a preference broker/manager. Data might not come from what's on disk but instead come from values in memory
10.8+: Sandbox apps keep data in ~/Library/Containers/[app id]
BOOLEAN is a CLASS that represents a True/False, Yes/No or 0/1 VALUE. It is normally used to switch something on or off.
plutil -lint is your friend if editing plist or launch* files
Remove all preferenes
defaults delete [app id]
Random defaults
defaults write /Library/Preferences/com.apple.loginwindow AdminHostInfo DSStatus
defaults write /Library/Preferences/com.apple.TimeMachine DoNotOfferNewDisksForBackup -bool YES
defaults write /Library/Preferences/.GlobalPrefernces PMPrintingExpandedStateForPrint -bool TRUE
defaults write com.apple.Safari WebKitOmitPDFSupport -bool YES
See Remote Disks
defaults write com.apple.NetworkBrowser EnableODiskBrowsing -bool YES
Disable window restoration for an application
defaults write com.apple.[appname] NSQuitAlwaysKeepsWindows -bool false
Disable Resume (10.8+)
defaults write com.apple.loginwindow TALLogoutSavesState -bool false
See file extensions in the Finder
defaults write NSGlobalDomain AppleShowAllExtensions -bool true; killall Finder
Disable App Nap
defaults write tld.company.app NSAppSleepDisabled -bool YES
Set FV2 pre-boot login screen login banner
defaults write /Library/Preferences/com.apple.loginwindow LoginwindowText “[Insert Text Here]”
Then touch /System/Library/PrivateFramworks/EFILogin.framework/Resources/EFIResourceBuilder.bundle/Contents/Resources
Disable Siri setup dialog
defaults write "${USER_TEMPLATE}"/Library/Preferences/com.apple.SetupAssistant DidSeeSiriSetup -bool TRUE
defaults write "${USER_HOME}"/Library/Preferences/com.apple.SetupAssistant DidSeeSiriSetup -bool TRUE
Disable Siri Menu Item
defaults write ~/Library/Preferences/com.apple.Siri.plist StatusMenuVisible -bool false
Enable Reminders.app debug menu
defaults write com.apple.reminders RemindersDebugMenu -boolean true
Set Finder new window to open User Home folder by default
defaults write com.apple.finder NewWindowTarget -string PfHm
Show Status Bar in Finder
defaults write com.apple.finder ShowStatusBar -bool TRUE
Set Finder server bookmarks
defaults write com.apple.sidebarlists favoriteservers -dict-add CustomListItems '( { Name = "afp://fqdn/"; URL = "smb://fqdn/"; } )'
Disable Back To My Mac in Sidebar
defaults write com.apple.sidebarlists networkbrowser "ControllerCustomListItemsCustomListItemsCustomListPropertiescom.apple.NetworkBrowser.backToMyMacEnabled"
Disable Bonjour in Sidebar
defaults write com.apple.sidebarlists networkbrowser "ControllerCustomListItemsCustomListItemsCustomListPropertiescom.apple.NetworkBrowser.bonjourEnabled"
Disable on Connect Server in Sidebar
defaults write com.apple.sidebarlists networkbrowser "ControllerCustomListItemsCustomListItemsCustomListPropertiescom.apple.NetworkBrowser.connectedEnabled"
10.13+ Fetch only basic SMB volume info
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool TRUE
Undo: defaults delete com.apple.desktopservices DSDontWriteNetworkStores
Set Safari to not open downloads automatically
defaults write com.apple.Safari AutoOpenSafeDownloads -bool FALSE
Set Safari to confirm when closing multiple pages
defaults write com.apple.Safari ConfirmClosingMultiplePages -bool TRUE
Set Safari homepage
defaults write com.apple.Safari HomePage -string [FQDN]
Show the Safari Debug Menu
defaults write com.apple.Safari IncludeInternalDebugMenu 1
Apple Push Notification Service (APNS), Configuration Profiles, DEP & MDM
Profiles: settings are interpreted by the OS and installed in /Library/Managed Preferences as plist files
Profiles-related files live in /var/db/ConfigurationProfiles
Binaries related to MDM
/usr/libexec/mdmclient
/usr/libexec/cloudconfigurationd
/System/Library/CoreServices/ManagedClient.app/Contents/MacOS/ManagedClient
/System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Resources/storeassetd
/System/Library/PrivateFrameworks/CommerceKit.framework/Versions/A/Resources/storedownloadd
Repository of users and services interacting with APNS (10.12+)
/Library/Preferences/com.apple.apsd.plist
Detailed APNS full status (10.12+)
/System/Library/PrivateFrameworks/ApplePushService.framework/apsctl status
APNS Status for the User Channel/Topic (aka User Level Profile)
/System/Library/PrivateFrameworks/ApplePushService.framework/apsctl status |grep -A 25 com.apple.mdmclient.agent.push.production
APNS Status for the Device Channel/Topic (aka Computer Level Profile)
/System/Library/PrivateFrameworks/ApplePushService.framework/apsctl status |grep -A 25 com.apple.mdmclient.daemon.push.production
CLI test for MDM enrollment
plutil -p /Library/Preferences/com.apple.apsd.plist | awk '/com.apple.mgmt/ {print $1}' | head -n 1 | sed s/com.apple.mgmt.External.//g
If a UUID is returned, machine is likely enrolled with an MDM.
The returned number will match the Mobile Device Management topic in the MDM Profile
Return the token for a service using APNS
/System/Library/PrivateFrameworks/ApplePushService.framework/apsctl status |grep '[application port name]' -A 21|awk '/token/ {gsub(/[<>]/,""); print $3,$4,$5,$6,$7,$8,$9,$10}'
e.g. /System/Library/PrivateFrameworks/ApplePushService.framework/apsctl status |grep 'com.apple.bird.push' -A 21|awk '/token/ {gsub(/[<>]/,""); print $3,$4,$5,$6,$7,$8,$9,$10}'
Enable debug logs for APNS
Also works to examine Profile Manager service on Server.app
defaults write /Library/Preferences/com.apple.apsd APSLogLevel -int 7
defaults write /Library/Preferences/com.apple.apsd APSWriteLogs -bool TRUE
killall apsd
tail -f /Library/Logs/apsd.log
Reset:
defaults write /Library/Preferences/com.apple.apsd APSWriteLogs -bool FALSE
defaults delete /Library/Preferences/com.apple.apsd APSLogLevel
killall apsd
Test connectivity to Apple related to APNS
nc -vz gateway.push.apple.com 2195
nc -vz gateway.push.apple.com 2196
nc -vz courier.push.apple.com 443
nc -vz feedback.push.apple.com 2195
nc -vz feedback.push.apple.com 2196
APNS Certificate Support
Contact Apple for help with Apple Push Notification service certificates
List computer level profiles (10.13+)
profiles list -all | awk /_computerlevel/
List computer level profiles (OSes older than 10.13)
profiles -Cv
Get names of enrollment profiles/Display DEP profile (10.13+)
profiles show -type enrollment (configuration | provisioning | enrollment)
Get names of enrollment profiles/Display DEP profile (OSes older than 10.13)
profiles -Cv | awk '/Enrollment/ { print $5,$6,$7,$8,$9 }'
Has a user approved MDM
profiles status -type enrollment | awk '/MDM/'
Get installed profiles (10.13+)
profiles show
Get installed profiles (OSes older than 10.13)
profiles -Lv (standard user gets that user's profiles. root gets sytem profiles)
profiles -P -o stdout [or path/to/out]
List information about installed configuration profiles
system_profiler SPConfigurationProfileDataType
Install profiles (10.13+)
profiles install -path /path/to/file
Install profiles (OSes older than 10.13)
profiles -I -F /path/to/file
Install profiles at reboot (OSes older than 10.13)
profiles -s -F /path/to/thisprofile.mobileconfig -f -v
Get detailed listing of installed profiles (10.12+)
/usr/libexec/mdmclient QueryInstalledProfiles
Location of Profiles Store
/private/var/db/ConfigurationProfiles/Store/
SIP restricted in 10.13+
Sign a config profile
/usr/bin/security cms -S -N "[Developer ID Installer cert or JPS certificate]" -i /path/to/unsigned profile -o /output/path/for/signed/profile
Unsign a profile
/usr/bin/security cms -D -i signed_profile_path -o unsigned_profile_path
Which server issued a machine's MDM certificate
system_profiler SPConfigurationProfileDataType | awk '/mdm/{print $3}' | tail -1 | awk -F / '{print $3}'
system_profiler SPConfigurationProfileDataType | awk '/ServerURL/ {print $3}' | awk -F / '{print $3}'
What is an enrolled machine's MDM server (OSes older than 10.13)
defaults read /private/var/db/ConfigurationProfiles/MDM_ComputerPrefs.plist APNSTokens_Production | awk '/https/'
Check if a machine was enrolled via DEP (10.13+)
profiles status -type enrollment | awk '/Enrolled/'
Print device enrollment configuration
profiles -e
Force a Machine To Refresh Device Enrollment Information From Apple Before Setup (10.13+)
This is an option under specific circumstance: Terminal is loaded at the OS Language picker before Setup is begun.
/var/db/ConfigurationProfiles/Settings/.cloudConfigNoActivationRecord will be present
profiles renew -type enrollment
Drives, Disk Images & Filesystem
See Security for Filevault items
For a machine with a single internal drive that is APFS formatted:
disk0 _should_ be the physical internal disk,
disk1 should be the synthesized APFS container and
disk2, disk3, etc _are likely_ additional external disks
Get details about the boot drive
diskutil info /
Get free space of boot drive
diskutil info / | awk '/ Free / {print $4,$5}'
Get more precise free space of boot drive for an APFS boot drive if Time Machine is enabled
diskutil info disk1s1 | awk '/Volume Free Space/ {print $4, $11}'
Mount a DMG file
hdiutil mount -noverify /path/to/the.dmg
Mount a DMG hosted on a website
hdiutil attach http://www.example.com/hosteddmg.dmg
Split image based on size
hdiutil segment -o firstSegname -segmentSize 4300M imageName.dmg
Split image based on segment count
hdiutil segment -o firstSegname -segmentCount 2 imageName.dmg
Get attributes of files and directories
GetFileInfo
In-depth Spotlight logging and diagnostics
mddiagnose
Remove quarantine attribute flags
xattr -d -r com.apple.quarantine /path/to/files
Strip ACLs
chmod -a# [acl number, likely 0] [path/to/folder] (that is a zero not an oh)
Make files/folders invisible
SetFile -a V
Get access and modification information for a file
stat -x
Open the Enclosing Folder for a File from the CLI
open -R .
Get Info on a File
file /path/to/file
Get verbose information on a file
mdls /path/to/file
Preserve ACLs during a copy
cp -p
Which files in a directory are SIP-protected
ls -alO (oh, not zero)
List Filevault-enabled users
fdesetup list -extended
Update FileVault's list of FileVault Enabled Users on Disk (10.13+)
diskutil apfs updatePreboot
Verify and Repair disk permissions
sudo /usr/libexec/repair_packages --verify --standard-pkgs --volume /
sudo /usr/libexec/repair_packages --repair --standard-pkgs --volume /
Dry run an APFS conversion (10.13+)
diskutil apfs convert /Volumes/MacHD -dryrun
Delete an APFS Container
diskutil apfs deleteContainer
Correct permissions for user with preferences quirks or unexpected prompts for admin credentials
chown -R [user] /Users/[user]
diskutil resetUserPermissions / [User's UID]
If that fails:
diskutil cs list
diskutil cs revert [uuid for problematic volume]
diskutil cs list | grep "Conversion Progress" Track progress
diskutil eraseDisk JHFS+ target disk0
Manually decrypt and erase a corrupted FileVault volume
diskutil cs list
diskutil cs delete [uuid for problematic volume]
Mount the PreBoot Partition
diskutil mount [Preboot disk slice, likely disk1s2]
Mount the Recovery Partition
diskutil mount [Preboot disk slice, likely disk1s3]
Explicitly set APFS boot volume to be the startup volume
/usr/sbin/bless --folder /System/Library/CoreServices/ --setBoot
Get Recovery HD OS Version (10.7-10.12 non-APFS)
1. diskutil list to find Recovery HD device info
2. diskutil mount /dev/disk/slice
3. defaults read /Volumes/Recovery\ HD/com.apple.recovery.boot/SystemVersion.plist ProductVersion
4. diskutil umount /Volumes/Recovery\ HD
Get Recovery Container OS Version (10.13+ APFS)
1. diskutil list to find Recovery container info
2. diskutil mount /dev/disk/slice
3. defaults read /Volumes/Recovery/[UUID]/SystemVersion.plist ProductVersion
4. diskutil umount /Volumes/Recovery
Boot into Recovery Mode
1. diskutil list
2. diskutil mount /dev/disk/slice
3. sudo bless —mount /Volumes/Recovery\ HD —setBoot —nextonly —file /Volumes/Recovery\ HD/com.apple.recovery.boot/boot.efi
3a. 10.13+ APFS: sudo bless —mount /Volumes/Recovery —setBoot —nextonly —file /Volumes/Recovery/com.apple.recovery.boot/boot.efi
4. shutdown -r now
Remove Local Time Machine snapshots
tmutil listlocalsnapshotdates
tmutil deletelocalsnapshots [date]
Hardware
Apple's 12-character Serial Number Format
Each serial number has five parts:
• Plant code: first three characters
• Year of manufacture: fourth character
- A,B,E,I,O,U are not used
- Each year has Early and Late options
- C = Early 2010 in scheme
• Week of manufacture: fifth character
- The vowels and B,S,Y or Z are not used
- Offset that depends on whether or not machine is Early or Late in the year
• Unit code: characters six through eight
- These are the only bits that will be unique among devices of the same model
• Device model identifier: last four characters
Various system/machine stats and info
sysctl -a
Get serial number
ioreg -c IOPlatformExpertDevice -d 2 |awk '/IOPlatformSerialNumber/ {print $3}' |sed s/\"//g
system_profiler SPHardwareDataType | awk '/Serial/ {print $4}'
nvram 4D1EDE05-38C7-4A6A-9CC6-4BCCA8B38C14:SSN | awk '{ gsub(/\%.*/, ""); print $NF }'
/usr/libexec/mdmclient QueryDeviceInformation | awk '/SerialNumber/ {print $3}' | head -n 1 | cut -c -1-12
Get hardware UUID
ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/ { split($0, line, "\""); printf("%s\n", line[4]); }'
system_profiler SPHardwareDataType | awk '/UUID/ {print $3}'
system_profiler SPHardwareDataType | grep UUID | cut -c 22-57
Get model (10.12+)
/usr/libexec/mdmclient QueryDeviceInformation | awk '/Model/&&/\,/ {print $3}'
Get Model Number information
curl -s http://support-sp.apple.com/sp/product?cc="[last four digits of serial number]"
Get EFI version
system_profiler SPHardwareDataType | awk '/ROM/ {print $4}'
Get a list of attached USB input devices
hidutil list | awk '/USB/ {print $9 $10 $11 $12}'
Get a list of attached Bluetooth input devices
hidutil list | awk '/Bluetooth/ {print $9 $10 $11 $12}'
Get a list of network ports
/usr/libexec/mdmclient QueryNetworkInformation
Get built-in Ethernet MAC
networksetup -getinfo Ethernet | awk '/Ethernet Address/ {print $3}'
Get a built-in Wi-Fi MAC
networksetup -getmacaddress "Wi-Fi" | awk '/Address/ {print $3}'
Get Thunderbolt Adapter MAC
networksetup -getmacaddress "Thunderbolt Ethernet" | awk '/Address/ {print $3}'
Get Display built-in Ethernet MAC
networksetup -getmacaddress "Display Ethernet" "Wi-Fi" | awk '/Address/ {print $3}'
Find My Mac registration information
nvram -p | grep fmm*
Computer name registered with Find My Mac
nvram -p | awk '/fmm-computer-name/ {print $2}'
Get Warranty Status of iOS 12.3+ Devices
Settings > General > About and then look for warranty expiration information
Is Hyper-Threading enabled
/usr/sbin/system_profiler SPHardwareDataType | /usr/bin/grep "Hyper-Threading Technology" | /usr/bin/awk -F ": " '{ print $2 }'
Get the Board-ID for a machine
ioreg -l | grep board-id
What machines are compatible with a particular version of an OS
cat /System/Library/CoreServices/PlatformSupport.plist
Does a machine have a T1 or T2 chip
/usr/libexec/remotectl list
What OS is the T1 or T2 chip running
/usr/libexec/remotectl show localbridge | awk '/OSVersion/ {print $3}'
What Bridge version is the T1 or T2 chip running
/usr/libexec/remotectl show localbridge | awk '/BridgeVersion/ {print $3}'
What is the model of the installed T1 or T2 chip
/usr/libexec/remotectl show localbridge | awk '/HWModel/ {print $3}'
Clear any information stored by the Touch Bar
Boot to Recovery and then xartutil --erase-all
Delete all enrolled fingerprints of all users on a Touchbar Mac
sudo bioutil --purge -s
Logging, Monitoring & Troubleshooting Tools
For best results with log, run with elevated privileges
It might take the system several minutes to collect and present data when using the "show" command
Recovery Boot Options
Command-R: Install the latest macOS that was installed on your Mac, without upgrading to a later version.
Option-Command-R: Upgrade to the latest macOS that is compatible with your Mac.
Shift-Option-Command-R (10.12.4+): Install the macOS that came with your Mac, or the version closest to it that is still available.
Access Terminal during OS install
cmd-option-shift-W will bring up Menu Bar
Hold command-option-control to enable option to pick Terminal from the Utilities Menu if needed
Access Terminal during macOS Setup
Command-Option-Control-T
User is root: At the Language Picker
User is _mbsetupuser: All other parts of setup
See logs during OS install
cmd-option-shift-W will bring up Menu Bar, then command-L
Kernel Panics
/Library/Logs/DiagnosticReports, loook for panic
Console Search Filter Properties
• date: format is YYYY-MM-DD
• proc:
• sub:
• pid:
10.12+ format of default output of log command
left to right
• Timestamp (YYYY-MM-DD HH:MM:SS.sssss-TZ)
• Thread ID
• Log Level Type (Default, Info, Debug, Error, Faults)
• Process ID
• Process Name (processingImagePath)
• Library (senderImagePath)
• Subsystem
• Category
• Message (eventMessage)
10.12+ log predicates
• category: Category of a log entry
• eventMessage: Searches the activity or message
• eventType: Type of events that created the entry (e.g. logEvent, traceEvent)
• messageType: Type or level of a log entry
• processImagePath: Name of the process that logged the event
• senderImagePath: Not all entries are created by processes, so this also includes libraries and executables
• subsystem: Name of the subsystem that logged an event
10.12+ log equivalent to tail -f /var/log/system.log
log stream --style syslog
10.12+ log stream with a time limit
log stream --style syslog --type log --timeout [time period m|h|d]
Output 10.12+ logs
log collect --output /path/to/collected.logarchive
Output a time period of 10.12+ logs
log collect --last [time period m|h|d] --output /path/to/collected.logarchive
Check for a specific event or term in 10.12+ logs
log show --predicate 'eventMessage contains "foo"' --last [time period m|h|d]
e.g. log show --predicate 'eventMessage contains "Safari"' --info -last 15m
Check for a events with a specific subsystem in 10.12+ logs
log show --predicate subsystem contains "foo"' --last [time period m|h|d]
e.g. log show --predicate 'subsystem contains "com.apple.finder"' --info --last 12h
Show user login information for past week
log show --predicate 'processImagePath contains "com.apple.AccountPolicyHelper"' --last 7d
Show "Previous Shutdown" causes for last day
log show --predicate 'eventMessage contains "Previous shutdown cause"' --last 24h
Show "Previous Shutdown" error info for past week
log show --predicate 'eventMessage contains "Previous Shutdown"' --last 7d
Show successfull screen locks
log show --predicate 'eventMessage contains "loginwindow sending screen is locked notification"' --start "YYYY-MM-DD 00:00:00"
Show successfull screensaver unlocks
log show --predicate 'eventMessage contains "Unlock succeeded"' --start "YYYY-MM-DD 00:00:00"
Show successfull machine wakes
log show --predicate 'eventMessage contains "Will connect user 0 because in full wake"' --start "YYYY-MM-DD 00:00:00"
Show last fifteen minutes of logs for a particular process
log show --predicate 'processID == [pid]' -last 15m
TCC / Privacy-related logging
log stream --debug --predicate 'subsystem == "com.apple.TCC" AND eventMessage BEGINSWITH "AttributionChain"'
Tail iCloud Document activity
brctl log --wait --shorten
System Error Codes
/System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Headers/MacErrors.h
Shutdown Cause Codes
0: Power disconnected
3: Hard shutdown
5: Normally initiated shutdown
-3: Multiple temperature sensors too high
-60: Bad master directory block, serious disk error
-61, -62: Unresponsive app resulting in forced shutdown
-64: Kernel panic, probably due to firmware issue
-71: Memory too hot
-74: Battery too hot
-75: MagSafe power adaptor communication problem
-78: Incorrect input current from power adaptor
-79: Incorrect current from battery
-86, -95: Proximity temperature (heatsink etc.) too high
-100: Power supply too hot
-101: Display too hot
-103: Battery voltage too low
-104: Unknown battery fault
-127: PMU/SMC forced shutdown for another cause
lsof options
lsof -i or lsof -iPn
Find open files by user: lsof -u username/UID
Find by process: lsof -p PID
See all the files an application has open
lsof -c [Application]
See network connections an application has opened
lsof -c [Application] | grep TCP
lsof -c [Application] | grep LISTEN
Get detailed filesytem usage
fs_usage -e -www
See file changes for an application or process as they happen
opensnoop -n [process name] SIP will impact use
See new process execution
execsnoop SIP will impact use
See I/O events as they occur
iosnoop SIP will impact use
Display top disk I/O events by process
iotop SIP will impact use
Per application TCP I/O
nettop -m tcp
I/O per network route
nettop -m route
Measure which CPU a process runs on
cpuwalk.d
See bytes of I/O by file and process
iofileb.d SIP will impact use
Sample process by CPU
sampleproc SIP will impact use
Get summary of machine's CPU, Power, Disk and Memory usage and process activity
systemstats --day current
Profile memory usage per application (10.9+)
footprint -pid [pid]
footprint -proc [process name]
Status of loaded kexts
kextstat
Dump system configuration data
scutil -p --snapshot
Look in /var/tmp for configd* files
Create disk IOPS table
iostat -do -c 3 -w 5 [disks]
do:old-style disk info
c: count
w:second wait interval
[disks]: Can list multiple disks
Determine which process is connected to a particular IP (aka what's downloading all that stuff)
1. `nettop -nc -m route`
_this gives a list of IPs. Find suspect IP_
2. `netstat -tn | awk '/[suspect IP from step 1]/'`
3. `lsof | awk '/[socket number returned in netstat for suspect IP]/' `
4. If needed, `ps ax | grep [PID found in lsof]`
Kickstart ARD with access and full privileges for admin users
sudo /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -access -on -users admin -privs -all -restart -agent -menu
Networking & Directory Services
mDNSResponder= one true source of DNS resolution in 10.5+ (with a few exceptions)
dig/nslookup/host = direct queries; have own resolvers
ping/dscl/dscacheutil/Safari = use mDNSResponder; info is cached
Native Attributes=LDAP | Standard Attributes=OD
Alternative to telnet in 10.13+
nc -vz [server] [port]
Flush DNS Cache (10.7+)
sudo dscacheutil -flushcache
sudo killall -HUP mDNSResponder
Clear Google Chrome DNS Cache
chrome://net-internals/#dns
“Clear host cache”
Resolve hostname to IP
dscacheutil -q host -a name [name]
Get DNS server used by a particular port
ipconfig getoption [port] domain_name_server
Set Computer/Host Name
scutil --set ComputerName [value]
scutil --set LocalHostName [value]
scutil --set HostName [value]
Dump mDNSResponder cache info to syslog
sudo killall -INFO mDNSResponder
Select system configuration location
scselect
What DNS servers is a machine using to resolve hosts
scutil --dns
Is a host/server available and reachable?
scutil --r [IP|hostname]
Light weigh portscanner (nmap)
/System/Library/CoreServices/Applications/Network\ Utility.app/Contents/Resources/stroke [IP or FQDN to scan] [starting port] [ending port]
Scan a subnet for AirPlay Hosts
dns-sd -B _airplay._tcp. local.
Get information about wireless connection
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -I
10.14+ Get information about wireless connection
wdutil info
Scan for wireless networks
/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -s
Enable routing between interfaces
sudo sysctl -w net.inet.ip.forwarding=1
sudo sysctl -w net.inet.fw.enable=1
Get detailed information about a mounted SMB share
smbutil statshares -a
Enable DirectoryService logs
slapconfig -enableslapdlog
Check a site's App Transport Security profile
nscurl --ats-diagnostics [URL]
Misc tools
dot_clean
networksetup
sso_util
Start iCloud log collection
ubcontrol --diagnose
Reset iCloud
ubcontrol --reset
Security
TCC stands for "transparency consent and control"
Get detailed list of System certificates (10.12+)
Same as Keychain Access > System > Certificates
/usr/libexec/mdmclient QueryCertificates
Get a list of admin users on a machine
dscl . read /Groups/admin GroupMembership
Check package signing
pkgutil --check-signature /path/to/.pkg
Strip a signing signature for a package
pkgutil --expand /path/to/package /path/to/destination; pkgutil --flatten /path/to/expanded /new/destination
Check the cert expiration date on an installer from the App Store
openssl pkcs7 -inform der -in /Applications/[app]/Contents/_MASReceipt/receipt -print_certs -text | grep "Not After :"
Find source URL for a downloaded file
xattr -px com.apple.metadata:kMDItemWhereFroms /path/to/dmgORpkg | xxd -r -p | plutil -p - | grep 0 | cut -c 7- | sed 's/"//g'
When was a downloaded file downloaded
xattr -px com.apple.metadata:kMDItemDownloadedDate /path/to/dmgORpkg | xxd -r -p | plutil -p - | grep 0 | cut -c 7-
Mimic Gatekeeper's check at the CLI
codesign --verify --no-strict --deep --verbose=4 /path/to/app
How to tell if an app is signed in detail
codesign -dvvv /path/to/app 2>&1
Find CodeRequirement details for a TCC Privacy Policy Configuration Profile
codesign --display -r- /path/to/app
Then parse the contents of the `designated =>` attribute
10.13+ User-Approved Kernel Extension Loading Database
/var/db/SystemPolicyConfiguration/KextPolicy
To verify that a kext is signed
kextutil -nt /path/to/.kext
View application notarization details
spctl -vvvv -a /path/to/app
Check an installer for notarization
spctl -a -t install -vvvv /path/to/some.pkg
Check an application for ticket stapling (requires CLI Tools)
/Library/Developer/CommandLineTools/usr/bin/stapler validate /path/to/apporkext
Check a kext for ticket stapling (requires CLI Tools)
/Library/Developer/CommandLineTools/usr/bin/stapler validate -v /path/to/kext
• Not signed: "Cannot download ticket. CDHash must be set"
• Not notarized: "pangpd.kext does not have a ticket stapled to it.”
• Notarized: "The validate action worked!”
Which apps in /Applications are stapled
for i in /Applications/* ; do /Library/Developer/CommandLineTools/usr/bin/stapler validate "${i}"|grep -B 1 worked;done
Get a list of user approved kexts (UAKEL)
sudo sqlite3 -line /var/db/SystemPolicyConfiguration/KextPolicy 'select * from kext_policy;'
sudo sqlite3 -csv /var/db/SystemPolicyConfiguration/KextPolicy 'select * from kext_policy;'
Get a list of Developer IDs for kexts approved by MDM
sudo sqlite3 -list /var/db/SystemPolicyConfiguration/KextPolicy 'select team_id from kext_policy_mdm;''
Get a list of kexts waiting for approval
sudo sqlite3 -list /var/db/SystemPolicyConfiguration/KextPolicy 'select bundle_id,developer_name,team_id from kext_policy where allowed="0"'
List System Preferences > Security & Privacy > Privacy > Accessibility
sudo sqlite3 /Library/Application\ Support/com.apple.TCC/TCC.db -list 'select client from access where service="kTCCServiceAccessibility"'
List System Preferences > Security & Privacy > Privacy > Full Disk Access
sudo sqlite3 /Library/Application\ Support/com.apple.TCC/TCC.db -list 'select client from access where service="kTCCServiceSystemPolicyAllFiles"'
List System Preferences > Security & Privacy > Privacy > Calendars (this is a per-user setting)
sqlite3 /Users/[user in question]/Library/Application\ Support/com.apple.TCC/TCC.db -list 'select client from access where service="kTCCServiceCalendar"'
List System Preferences > Security & Privacy > Privacy > Contacts (this is a per-user setting)
sqlite3 /Users/[user in question]/Library/Application\ Support/com.apple.TCC/TCC.db -list 'select client from access where service="kTCCServiceAddressBook"'
List System Preferences > Security & Privacy > Privacy > Photos (this is a per-user setting)
sqlite3 /Users/[user in question]/Library/Application\ Support/com.apple.TCC/TCC.db -list 'select client from access where service="kTCCServicePhotos"'
List System Preferences > Security & Privacy > Privacy > Camera (this is a per-user setting)
sqlite3 /Users/[user in question]/Library/Application\ Support/com.apple.TCC/TCC.db -list 'select client from access where service="kTCCServiceCamera"'
List System Preferences > Security & Privacy > Privacy > Microphone (this is a per-user setting)
sqlite3 /Users/[user in question]/Library/Application\ Support/com.apple.TCC/TCC.db -list 'select client from access where service="kTCCServiceMicrophone"'
List System Preferences > Security & Privacy > Privacy > Automation (this is a per-user setting)
sqlite3 /Users/[user in question]/Library/Application\ Support/com.apple.TCC/TCC.db -list 'select client from access where service="kTCCServiceAppleEvents"'
Reset access to personal data
tccutil reset [app name]
SecureToken
SecureToken is an APFS file system attribute. Having SecureToken set signifies that a user can unlock a FileVault-encrypted
container on an APFS-formatted volume. On machines with FileVault enabled, it is imperative that any user using the machine
have SecureToken set or else they will not be able to unlock the encrypted drive. Without the SecureToken bit on a user account,
that user will not be able to authenticate at the FileVault pre-OS login screen. The OS should prevent the deletion of the last
user with SecureToken on the system.
SecureToken is a special attribute. SecureToken is an APFS file system mechanism, specifically one that is part of the
software encryption built into APFS. SecureToken is keybag that maintains credentials for crypto uses able to work
with the disk. SecureToken is generated during the time when the OS is first installed and initialized.If no users
on a system have SecureToken, it can not be bootstrapped or assigned to a user via a backdoor. Only a user with
SecureToken can grant SecureToken to another user; it is a chain of trust. Once SecureToken's existance on a system has come
into being, you can no longer create a brand new SecureToken instance or modify SecureToken with having SecureToken.
SecureToken should be automatically granted:
• To the first user created by SetupAssistant on a new machine/fresh OS install
• For a user created by the MDM createuser command for machines enrolled in DEP
• For existing FileVault users on a machine that has been upgraded to 10.13 or 10.14
• To directory users on a properly bound machine
• To users created in the GUI via System Preferences > Accounts if the admin account doing the creation has SecureToken
• To users created via the CLI with sysadminctl if the admin account doing the creation has SecureToken and if SecureToken is explicitly granted to the newly created user
• If FileVault is enabled on a machine, the Personal Recovery Key is actually a user in APFS that has been granted SecureToken
Check a user's SecureToken status
sysadminctl -secureTokenStatus [user]
Grant SecureToken to a user
sysadminctl -adminUser [admin user] -adminPassword [admin's pass] -secureTokenOn [user] -password [user's pass]
Which FileVault-enabled user unlocked the drive
echo $(ioreg -l -w0 -p IODeviceTree | grep efilogin-unlock-ident) | grep -Eo "[A-F0-9]{8}-[A-F0-9]{4}-4[A-F0-9]{3}-[89AB][A-F0-9]{3}-[A-F0-9]{12}"
Cross reference with GeneratedUID value in user records
List users with SecureToken, including special users like the Personal Recovery Key
diskutil apfs listCryptoUsers [diskSlice]
Confirm users have SecureToken registered on disk
1. diskutil apfs listUsers / | awk '/\+--/' | sed s/\+--//g
2. dscl /Local/Default -list /Users GeneratedUID | grep -v "^_" | grep -v root | grep -v nobody | grep -v daemon
3. Match the UID from diskutil to the UID returned by dscl
Who are the FileVault-enabled Users on disk
1. Mount Preboot environment: diskutil mount disk1s2
2. plutil -p /Volumes/Preboot/[UUID]/var/db/AdminUserRecoveryInfo.plist
10.13+ encrypted FileVault Personal Recovery Key location
/var/db/FileVaultPRK.dat
Filevault presents “Update Needed” Error
The "Updated Needed" means that the EFI login lost the icon information. Run the following to correct
sudo fdesetup sync
What malware has Apple flagged in the Xprotect definitions (10.9+)
cat /System/Library/CoreServices/XProtect.bundle/Contents/Resources/XProtect.yara | grep -A 1 meta | awk '/description/' | sed -e 's/description//g' -e 's/\=//g'
Get malware definitions date (10.6 -10.8)
defaults read /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/XProtect.meta LastModification
Get Malware definitions date (10.9+)
stat -x /System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/XProtect.meta.plist | grep Modify | awk '{print $2,$3,$4,$5,$6}'
Force update of malware definitions (10.6 - 10.8)
sudo /usr/libexec/XProtectUpdater
Force update of malware definitions (10.9-10.11)
softwareupdate --background-critical
Automatic updates must be enabled first: softwareupdate --schedule on
Force update of Xprotect, Gatekeeper and MRT definitions (110.12)
softwareupdate -l --include-config-data
softwareupdate -i --include-config-data
Start the application level firewall
launchctl load /System/Library/LaunchDaemons/com.apple.alf.agent.plist
launchctl load /System/Library/LaunchAgents/com.apple.alf.useragent.plist
Stop the application level firewall
launchctl unload /System/Library/LaunchDaemons/com.apple.alf.agent.plist
launchctl unload /System/Library/LaunchAgents/com.apple.alf.useragent.plist
Allow an outbound connection in application layer firewall
socketfilterfw -t"/Applications/[app]/Contents/MacOS/[app]"
Dump the contents of X509 cert
openssl x509 -inform der -in [cert].cer -noout -text
Decrypt base64 encoded text
echo [coded text] | base64 --decode
Software Update & Caching Service
System data files == softwareupdate -background-critical/--include-config-data == XProtect, GateKeeper Opaque Whitelist and Incompatible Kext Configuration Data
Caching Server clients must be able to ping gs.apple.com before they start trusting local caching server
CatalogURLs
10.14: https://swscan.apple.com/content/catalogs/others/index-10.14-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz
10.13: https://swscan.apple.com/content/catalogs/others/index-10.13-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz
10.12: https://swscan.apple.com/content/catalogs/others/index-10.12-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz
10.11: https://swscan.apple.com/content/catalogs/others/index-10.11-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog.gz
10.10: http://swscan.apple.com/content/catalogs/others/index-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog
Download pkgs direct from Apple's Software Update Catalogs'
Get pkg URLs: curl -s $(strings /System/Library/PrivateFrameworks/SoftwareUpdate.framework/SoftwareUpdate | awk '/https/ && /sucatalog/') | awk '/[AppName w/out brackets]/ && /pkg/'
With found URLs: curl -O [URL]
Determine which SU server a machine is pulling updates from
grep "Using catalog" /var/log/install.log
Which SUS Server is a Profile directing a machine to
system_profiler SPConfigurationProfileDataType | grep CatalogURL | awk '{print $3}'| cut -c 2-88
Use Apple SUS when machines are configured for own SUS (Config Profiles might not allow override. 10.11+ might not respect)
softwareupdate -l --CatalogURL "http://swscan.apple.com/content/catalogs/others/index-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog"
Set an updates catalog (10.11+)
softwareupdate --set-catalog https://swscan.apple.com/content/catalogs/others/[catalog]
Reset updates catalog
softwareupdate --clear-catalog
Temporarily use alt SUS (Config Profiles might not allow override)
softwareupdate -i --CatalogURL "http://su.domain_name.com:8088/index.sucatalog
Force Quickscan for just one type of update (10.13+)
softwareupdate --list --product-types [product, e.g. macOS or Safari]
Have the system ignore or block installation of a particular update
/usr/sbin/softwareupdate --ignore "[update name]
e.g. sudo /usr/sbin/softwareupdate --ignore "Security Update 2018-001"
Apple has a habit of including trailing spaces in names and these spaces must be included
Change Software Update Server
defaults write /Library/Preferences/com.apple.SoftwareUpdate CatalogURL http://FWDNofSUS:8088/index.sucatalog
Which updates are available for a machine
defaults read /Library/Preferences/com.apple.SoftwareUpdate.plist LastUpdatesAvailable
Get a list of installed updates by date
system_profiler SPInstallHistoryDataType
Enable Xprotect and Gatekeeper updates to be installed automatically
defaults /Library/Preferences/com.apple.SoftwareUpdateConfigDataInstall -bool TRUE
Enable automatic installation of security updates
defaults /Library/Preferences/com.apple.SoftwareUpdateCriticalUpdateInstall -bool TRUE
Enable automatic installation of app updates from the App Store
defaults /Library/Preferences/com.apple.commerceAutoUpdate -bool TRUE
Enable automatic installation of OS X updates
defaults /Library/Preferences/com.apple.commerceAutoUpdateRestartRequired -bool TRUE
Enable automatic software update check
defaults /Library/Preferences/com.apple.SoftwareUpdateAutomaticCheckEnabled -bool TRUE
When was the last time a Xprotect Config Data package was installed
pkgutil --pkg-info $(pkgutil --pkgs | awk '/com.apple.pkg.XProtectPlistConfigData/' | tail -n 1) | date -r $(awk '/install/ { print $2 }')| awk '{ print $2,$3,$6 }'
What is updated by “Install system data files and security updates” in 10.14+
• Core Services Application Configuration Data: Blocks incompatible apps from being launched
• EFICheck AllowListAll: Verifies that Apple provided the firmware for your Mac
• Gatekeeper Configuration Data
• Incompatible Kernel Extension Configuration Data: Blocks incompatible kernel extensions that may adversely affect your Mac
• MRTConfigData: Removes known malware
• TCC Configuration Data: Improves compatibility of specified software with macOS security features
• XProtectPlistConfigData
Which Caching Server is a machine using (10.12+)
/usr/bin/AssetCacheLocatorUtil 2>&1 | grep guid | awk '{print$4}' | sed 's/^\(.*\):.*$/\1/' | uniq
What Caching Server is a machine using
sudo find /var/folders -iname diskcache.plist -exec plutil -p {} \; | awk '/localAddressAndPort/ {print $3}' | head -n 1 | sed 's/\"//g'
Caching Service Prefs file (10.13+)
/Library/Preferences/com.apple.AssetCache.plist (must be owned by _asset_cache user and group)
Caching Service Control (10.13+)
/usr/bin/AssetCacheManagerUtil
• AssetCacheManagerUtil activate: Enable Service
• AssetCacheManagerUtil flushCache
• AssetCacheManagerUtil status
• AssetCacheManagerUtil settings
• AssetCacheManagerUtil reloadSettings
Monitor Caching Server activity (OSes prior to 10.13)
tail -f /Library/Server/Caching/Logs/Debug.log
System (including launchd and printers)
/var/folders/zz must be 755
Use dscl in single user mode
/bin/launchctl load /System/Library/LaunchDaemons/com.apple.DirectoryServices.plist &
SIP Whitelists
/System/Library/Sandbox/rootless.conf
/System/Library/Sandbox/Compatibility.bundle/Contents/Resources/paths
Turn on remote login
systemsetup -setremotelogin on
Create the com.apple.access_ssh group
Needed to allow proper SSH access
dseditgroup -o create -q com.apple.access_ssh
Add the admin group to com.apple.access_ssh
Needed to allow proper SSH access
dseditgroup -o edit -a admin -t group com.apple.access_ssh
Get the time from time server
/usr/sbin/systemsetup -getnetworktimeserver
Set Timezone
systemsetup -settimezone America/Chicago
Use "/usr/sbin/systemsetup -listtimezones" to see a list of available list time zones
Disable sleep image
sudo pmset -a hibernatemode 0
sudo nvram "use-nvramrc?"=false
/etc/newsyslog.conf
file permissions mode | how many copies to keep | size | when to roll | flags
Turn off printer sharing
1. lpstat -p | awk '{print $2}' | xargs -I{} lpadmin -p {} -o printer-is-shared=false
2. cupsctl —no-share-printers
Get a list of printers v1
lpstat -a
Get a list of printers v2
plutil -p /Library/Preferences/org.cups.printers.plist | awk '/printer-info/ {print $3,$4,$5}'
Get options for a particular printer
lpoptions -p [name] -l
What options are potentially available to set for a printer
lpoptions -l /Library/Printers/PPD/[printer ppd.gz]
What printers are configured on a machine
sudo cat /etc/cups/printers.conf | awk '/Info/' | cut -c 6-99
List a user's launchd items
launchctl print gui/[user's UID]
List system launchd itmes
launchctl print system
Get detailed information about a particular launchagent
launchctl print gui/[user UID]/[com.company.launchagent]
Load a launchagent (10.10+)
launchctl bootstrap gui/[user UID] /Library/LaunchAgents/com.company.launchagent.plist
Unload a launchagent (10.10+)
launchctl bootout gui/[user UID] /Library/LaunchAgents/com.company.launchagent.plist
Unlock a locked file
chflags -R nouchg /Path/To/File/or/Locked/Folder
Find PostScript Type1 Fonts
mdfind 'kMDItemKind = "PostScript Type 1 outline font"'
User
Get currently logged in user (Fast User Switching safe)
python -c 'from SystemConfiguration import SCDynamicStoreCopyConsoleUser; import sys; username = (SCDynamicStoreCopyConsoleUser(None, None, None) or [None])[0]; username = [username,""][username in [u"loginwindow", None, u""]]; sys.stdout.write(username + "\n");'
Alternate versions of current logged in user
/usr/bin/w | grep console | awk '{print $1}'
ls -l /dev/console | awk '{print $3}'
id -P | awk -F: '{print $1}'
Force a user logout
launchctl bootout gui/$(id -u [user name])
User info lookup
dscacheutil -q user -a name [name]
Get a user's UUID
dscl . read /Users/[user shortname] GeneratedUID
When was an account created
Dump creationTime from user record in dscl, then date -r [seconds]
Get a list of user UUID's on a machine not including service or OS users
dscl /Local/Default -list /Users GeneratedUID | grep -v "^_" | grep -v root | grep -v nobody | grep -v daemon
Get a list of user IDs
dscl . -list /Users UniqueID
List of local users on machine
dscl . list /Users UniqueID | awk '$2 >500 { print $1 }
Get user's /var/folders Cache Folder
getconf DARWIN_USER_CACHE_DIR
Get user's /var/folders Temp Folder
getconf DARWIN_USER_TEMP_DIR
What account is signed into iCloud
defaults read /Users/[user name]/Library/Preferences/MobileMeAccounts.plist | awk '/AccountID/ {print $3}'
Mobile account files
Password: /var/db/shadow/hash/[dsattrTypeStandard:GeneratedUID]
Account Info: ~/.account
Change local user password
dscl . -passwd /Users/username thenewpasswordhere
10.11+: sysadminctl -resetPasswordFor [local user name] -newPassword [new password]
Create a user (10.11+)
sysadminctl -addUser [-fullName ] [-UID ] [-shell ] [-password ] [-hint ] [-home ] [-picture ]
10.13 requires using -secureTokenOn when creating an admin user
Create a user with SecureToken
Requires admin user with SecureToken
sysadminctl -adminUser [admin with SecureToken] -adminPassword - -addUser [new user] -fullName "[new user full name]" -UID [id number] -password - -secureTokenOn -home /Users/[new user]
Cleanly remove a user (10.11+)
Removes any user processes, their home folder, public shares, cached credentials and disables Back to My Mac for the user
sysadminctl -deleteUser [user]
Server-specific
Server CLI tools
serveradmin
ServerBackup
webappctl
Server (v3+) DNS Tool: /Applications/Server.app/Contents/ServerRoot/System/Library/PrivateFrameworks/DNSManager.framework/dnsconfig
Keep shares mounted after log out
sudo defaults write /Library/Preferences/SystemConfiguration/autodiskmount AutomountDisksWithoutUserLogin -bool YES
Reset the web service
sudo serveradmin command web:command=restoreFactorySettings
Programatically start PHP and Python apps hosted by Server.app
sudo webappctl start com.apple.webapp.php
sudo webappctl stop com.apple.webapp.php
sudo webappctl start com.apple.webapp.wsgi
sudo webappctl stop com.apple.webapp.wsgi
Get full network settings for a server
serveradmin settings network
What ports is a server listening on
netstat -an
Dump DNS information
/Applications/Server.app/Contents/ServerRoot/System/Library/PrivateFrameworks/DNSManager.framework/dnsconfig list
Get information about a zone
/Applications/Server.app/Contents/ServerRoot/System/Library/PrivateFrameworks/DNSManager.framework/dnsconfig --zone=[domain]
View a particular machine's information
/Applications/Server.app/Contents/ServerRoot/System/Library/PrivateFrameworks/DNSManager.framework/dnsconfig --rr=[FQDN of machine]
Misc
Convert an audio file
afconvert
Toggle visibility of hidden files in the Finder
Press Shift + Command + . (period)
Display a notication
osascript -e 'display notification "This is the window body" with title "Window Header!"'
Force the Setup Assistant to Run
sudo /System/Library/CoreServices/Setup Assistant.app/Contents/MacOS/Setup Assistant -MBDebug -MiniBuddyYes
"What's New" notifications
/System/Library/PrivateFrameworks/Tourist.framework/Versions/A/Resources/touristd
Apple Service Domains
Apple makes extensive use of Akamai, AWS Cloudfront CDNs, so not all addresses will resolve to an Apple 17.0.0.0 address
aaplimg.com
Apple's in-house CDN
albert.apple.com
Used for activation
appldnld.apple.com
iOS Firmware delivery
ax.itunes.apple.com
Apple search
buy.itunes.com
Purchase and account validation
captive.apple.com
Used for captive network testing. Also used attwifi.apple.com
*.cdn-apple.com
Apple CDN network
cl*.apple.com
Used by locationd
configuration.apple.com
configuration.apple.com is an alias for configuration.apple.com.edgekey.net, which will resolve to various Akamai IPs
deimos * .apple.com
iTunes U
deploy.apple.com
DEP and VPP portal. api-applecareconnect-ept*.apple.com, acc-ipt.apple.com, mdmenrollment.apple.com are also used for DEP
*.digicert.com
Used for certificate validation. crl3.digicert.com, crl4.digicert.com and ocsp.digicert.com are specifically used for Apple Business Manager and Apple School Manager
evintl-ocsp.verisign.com
Used for certificate validation
evsecure-ocsp.verisign.com
Used for certificate validation
gg*.apple.com
iOS update servers
gnf-mdn.apple.com & gnf-mr.apple.com
Deliver EFI updates for Touchbar Macs
gs.apple.com
gs.apple.com is an alias for gs.apple.com.akadns.net, which will resolve to various Apple 17.0.0.0 IPs
Used for:
• iOS signature validation
• destination of the personalization manifest from a T1 or T2-equipped Macs
• LaunchServices contacts to verify app stapling ticket revocation state
• validate update servers used by the Caching service.
gsp*.apple.com & gsp*-ssl.apple.com
Used with geolocation services
ig.apple.com
Used with Touchbar Macs
iprofiles.apple.com
Uses by Apple Business Manager and Apple School Manager. Initial service URL/endpoint for a DEP device to discover whether Apple has an MDM configured for the device
lcdn-locator.apple.com
Likely used with Caching Service
lcdn-registration.apple.com
Caching Service registration
littlebuddy.apple.com
Used by Setup Assistant
mesu.apple.com
iOS software updates
metrics.apple.com
Apple analytics
mzstatic.com
Apple in-house CDN
ocsp.apple.com
Used to validate certificates
panic.apple.com
Associated with error reporting
phobos.apple.com
iTunes
push.apple.com
Resolves to various Apple 17.0.0.0 IPs. Used for APNS. Includes gateway.push.apple.com, feedback.push.apple.com and courier.push.apple.com
For push notification services. api.development.push.apple.com:443 and api.push.apple.com:443 are the HTTP/2 compatible sites.
skl.apple.com
Used with Touchbar Macs
su.itunes.apple.com
App updates
swcdnlocator.apple.com
Related to Apple Mac Software Update
swscan.apple.com
Front end to Apple Mac Software Update
swdist.apple.com
Related to Apple Mac Software Update
*.symcb.com
Used for certificate validation
*.symcd.com
Used for certificate validation
Built-in apps and binaries and their related service domains
Airport Utility
Can connect to apfw.apple.com and apsu.apple.com
assistantd
Associated with Siri, dictation, etc. Makes calls to various Apple 17.0.0.0 IPs
bird
iCloud documents daemon. brctl is the binary used to interact with it
cloudconfigurationd
The Device Enrollment client daemon, which is responsible for communicating with the DEP API and retrieving Device Enrollment profiles. Can connect to iprofiles.apple.com and suconfig.apple.com.
Safari
Can connect to extensions.apple.com and plugins.apple.com
SpotlightNetHelper
Can connect to cloudfront.net, init.itunes.apple.com, api-glb-chi.smoot.apple.com and api.smoot.apple.com
storeaccountd
Can connect to phobos.apple.com, ax.init.itunes.apple.com and play.itunes.apple.com
SubmitDiagInfo
Can connect to radarsubmissions.apple.com