#!/bin/zsh # ProfiLab Health - agent for macOS - v1.0.0 # # What it does (English, so that anyone can check it): # Once a day and at start-up it reads the HARDWARE and MAINTENANCE state of # this Mac and sends a short report to ProfiLab (https://profilab.org), so # that we can warn you before something breaks. # # What it sends: model and serial number, macOS version and uptime, memory # size, disk model/size/SMART status (and wear, if smartctl is installed), # free space on the system disk, battery health and cycle count, whether # Time Machine is set up and the date of the last backup, Gatekeeper / # FileVault / firewall on or off, and the date of the last macOS update. # # What it never reads or sends: your files, file or document names, browser # history, passwords, e-mail, messages, photos, screen, keystrokes, # location, the computer name or user names. It cannot control the Mac: # it only sends, and it accepts no commands from the server. # # See exactly what would be sent, without sending anything: # zsh profilab-health.sh --dry-run # # Install (as administrator): sudo zsh profilab-health.sh --install # Remove everything: sudo zsh "/Library/Application Support/ProfiLab/Health/profilab-health.sh" --uninstall # # More, in Spanish, English, Russian and Ukrainian: # https://profilab.org/mantenimiento-informatico/salud-de-equipos/ emulate -L zsh setopt pipe_fail no_nomatch export PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/libexec # Plain C locale: decimal point in numbers and English tool messages, # whatever the language of this Mac. export LC_ALL=C readonly VERSION=1.0.0 readonly DEFAULT_ENDPOINT=https://profilab.org/api/fleet/report readonly BASE_DIR="/Library/Application Support/ProfiLab/Health" readonly LABEL=org.profilab.health readonly PLIST=/Library/LaunchDaemons/$LABEL.plist readonly SELF=${0:A} MODE=send TOKEN= ENDPOINT= usage() { print -r -- "Usage: zsh profilab-health.sh [--dry-run | --install TOKEN | --uninstall] [--token TOKEN] [--endpoint URL]" } die() { print -r -- "ProfiLab Health: $*" >&2; exit 1 } while (( $# )); do case $1 in --dry-run) MODE=dry ;; --install) MODE=install; (( $# >= 2 )) && { TOKEN=$2; shift } ;; --uninstall) MODE=uninstall ;; --token) (( $# >= 2 )) && { TOKEN=$2; shift } ;; --endpoint) (( $# >= 2 )) && { ENDPOINT=$2; shift } ;; -h|--help) usage; exit 0 ;; *) usage; exit 2 ;; esac shift done TMP=$(mktemp -d -t profilab-health) || die "cannot create a temporary folder" trap 'rm -rf "$TMP"' EXIT # --- Small helpers -------------------------------------------------------- # Value from a plist file by key path, or nothing (missing key is not an error). pb() { /usr/libexec/PlistBuddy -c "Print :$2" "$1" 2>/dev/null } # JSON string (or null). Values come from the system, but escape them anyway. jstr() { local s=$1 if [[ -z $s ]]; then print -rn -- null; return; fi s=${s//\\/\\\\} s=${s//\"/\\\"} s=${s//[[:cntrl:]]/ } print -rn -- "\"$s\"" } # JSON number (or null). jnum() { if [[ $1 =~ '^-?[0-9]+([.][0-9]+)?$' ]]; then print -rn -- $1; else print -rn -- null; fi } # JSON true/false (or null). jbool() { case $1 in true) print -rn -- true ;; false) print -rn -- false ;; *) print -rn -- null ;; esac } # Local "YYYY-MM-DD-HHMMSS" -> ISO in UTC. stamp_iso() { local sec sec=$(date -j -f "%Y-%m-%d-%H%M%S" "$1" "+%s" 2>/dev/null) || return 1 date -u -r "$sec" "+%Y-%m-%dT%H:%M:%SZ" } # Short, non-reversible id for a disk: the serial itself is not sent. short_id() { print -rn -- "$1" | shasum -a 256 | cut -c1-10 } # --- Collect -------------------------------------------------------------- collect() { local H=$TMP/hw.plist P=$TMP/power.plist B=$TMP/bat.plist system_profiler -xml SPHardwareDataType > $H 2>/dev/null system_profiler -xml SPPowerDataType > $P 2>/dev/null ioreg -rn AppleSmartBattery -a > $B 2>/dev/null local model_name=$(pb $H 0:_items:0:machine_name) local model_id=$(pb $H 0:_items:0:machine_model) local serial=$(pb $H 0:_items:0:serial_number) local model=$model_name [[ -n $model_id ]] && model="$model_name ($model_id)" local cpu=$(sysctl -n machdep.cpu.brand_string 2>/dev/null) local mem=$(sysctl -n hw.memsize 2>/dev/null) local ram_gb= [[ $mem == <-> ]] && ram_gb=$(( mem / 1073741824 )) local os_ver=$(sw_vers -productVersion 2>/dev/null) local os_build=$(sw_vers -buildVersion 2>/dev/null) local boot=$(sysctl -n kern.boottime 2>/dev/null) uptime_h= if [[ $boot =~ 'sec = ([0-9]+)' ]]; then uptime_h=$(( ( $(date +%s) - ${match[1]} ) / 3600 )) fi # Battery: Apple's own "maximum capacity" (what Settings > Battery shows), # plus design and full capacity from the battery controller. local battery=null dtype=desktop if [[ $(pb $P 0:_items:0:_name) == spbattery_information ]]; then dtype=laptop local cycles=$(pb $P 0:_items:0:sppower_battery_health_info:sppower_battery_cycle_count) local cond=$(pb $P 0:_items:0:sppower_battery_health_info:sppower_battery_health) local maxcap=$(pb $P 0:_items:0:sppower_battery_health_info:sppower_battery_health_maximum_capacity) maxcap=${maxcap//[^0-9]/} local design=$(pb $B 0:DesignCapacity) [[ -z $design ]] && design=$(pb $B 0:BatteryData:DesignCapacity) local full=$(pb $B 0:AppleRawMaxCapacity) [[ -z $full ]] && full=$(pb $B 0:BatteryData:AppleRawMaxCapacity) [[ -z $cycles ]] && cycles=$(pb $B 0:CycleCount) battery="{\"design\":$(jnum $design),\"full\":$(jnum $full),\"healthPct\":$(jnum $maxcap),\"cycles\":$(jnum $cycles),\"condition\":$(jstr $cond)}" fi # Disks: internal NVMe and SATA drives with their SMART status. local smartctl= for c in /opt/homebrew/sbin/smartctl /opt/homebrew/bin/smartctl /usr/local/sbin/smartctl /usr/local/bin/smartctl; do [[ -x $c ]] && { smartctl=$c; break } done local -a disks local T F i j base name size smart media bus dserial health sj wear temp poh merr realloc pend unc passed k id for T in SPNVMeDataType SPSerialATADataType; do F=$TMP/$T.plist system_profiler -xml $T > $F 2>/dev/null || continue i=0 while [[ -n $(pb $F "0:_items:$i:_name") ]] && (( i < 8 )); do j=0 while [[ -n $(pb $F "0:_items:$i:_items:$j:_name") ]] && (( j < 8 )); do base="0:_items:$i:_items:$j" name=$(pb $F ${base}:device_model); [[ -z $name ]] && name=$(pb $F ${base}:_name) size=$(pb $F ${base}:size_in_bytes) smart=$(pb $F ${base}:smart_status) dserial=$(pb $F ${base}:device_serial) if [[ $T == SPNVMeDataType ]]; then media=ssd; bus=nvme else bus=sata case $(pb $F ${base}:spsata_medium_type) in *Solid*) media=ssd ;; *Rotational*) media=hdd ;; *) media= ;; esac fi case $smart in Verified) health=ok ;; Failing) health=failing ;; *About*|*Warn*) health=warning ;; *) health= ;; esac wear= temp= poh= merr= realloc= pend= unc= # Wear and error counters only if smartctl (smartmontools) is present. if [[ -n $smartctl ]]; then local bsd=$(pb $F ${base}:bsd_name) sj=$TMP/smart-$i-$j.json if [[ -n $bsd ]] && $smartctl -a -j /dev/$bsd > $sj 2>/dev/null || [[ -s $sj ]]; then wear=$(plutil -extract nvme_smart_health_information_log.percentage_used raw -o - $sj 2>/dev/null) merr=$(plutil -extract nvme_smart_health_information_log.media_errors raw -o - $sj 2>/dev/null) poh=$(plutil -extract power_on_time.hours raw -o - $sj 2>/dev/null) temp=$(plutil -extract temperature.current raw -o - $sj 2>/dev/null) passed=$(plutil -extract smart_status.passed raw -o - $sj 2>/dev/null) [[ $passed == false ]] && health=failing for k in {0..29}; do id=$(plutil -extract ata_smart_attributes.table.$k.id raw -o - $sj 2>/dev/null) || break case $id in 5) realloc=$(plutil -extract ata_smart_attributes.table.$k.raw.value raw -o - $sj 2>/dev/null) ;; 197) pend=$(plutil -extract ata_smart_attributes.table.$k.raw.value raw -o - $sj 2>/dev/null) ;; 198) unc=$(plutil -extract ata_smart_attributes.table.$k.raw.value raw -o - $sj 2>/dev/null) ;; esac done fi fi local size_gb= [[ $size == <-> ]] && size_gb=$(( size / 1000000000 )) disks+=("{\"id\":$(jstr m$(short_id "${dserial:-$T$i$j}")),\"name\":$(jstr $name),\"media\":$(jstr $media),\"bus\":$(jstr $bus),\"sizeGb\":$(jnum $size_gb),\"health\":$(jstr $health),\"wearPct\":$(jnum $wear),\"tempC\":$(jnum $temp),\"powerOnHours\":$(jnum $poh),\"errors\":{\"reallocated\":$(jnum $realloc),\"pending\":$(jnum $pend),\"uncorrectable\":$(jnum $unc),\"mediaErrors\":$(jnum $merr)}}") (( j++ )) done (( i++ )) done done # Free space on the system disk (APFS: the whole container). local -a df_line df_line=(${(z)$(df -Pk / 2>/dev/null | tail -1)}) local vol_size= vol_free= if [[ ${df_line[2]} == <-> && ${df_line[4]} == <-> ]]; then # Gigabytes as Finder counts them (10^9 bytes). vol_size=$(printf '%.1f' $(( df_line[2] * 1024.0 / 1000000000 ))) vol_free=$(printf '%.1f' $(( df_line[4] * 1024.0 / 1000000000 ))) fi # Time Machine: is a destination set up, and when was the last backup. local tm_conf= tm_last= local tmd=$(tmutil destinationinfo 2>&1) if [[ $tmd == *"No destinations configured"* ]]; then tm_conf=false elif [[ $tmd == *"Name"* || $tmd == *"ID"* ]]; then tm_conf=true fi local latest=$(tmutil latestbackup 2>/dev/null) if [[ $latest =~ '([0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{6})' ]]; then tm_last=$(stamp_iso ${match[1]}) fi if [[ -z $tm_last && -r /Library/Preferences/com.apple.TimeMachine.plist ]]; then tm_last=$(plutil -convert xml1 -o - /Library/Preferences/com.apple.TimeMachine.plist 2>/dev/null | awk '/SnapshotDates<\/key>/{f=1;next} f&&/<\/array>/{f=0} f&&//{gsub(/.*|<\/date>.*/,"");print}' | sort | tail -1) fi [[ -n $tm_last ]] && tm_conf=true # Protection switches (on/off only). local gk= fv= fw= case $(spctl --status 2>/dev/null) in *enabled*) gk=true ;; *disabled*) gk=false ;; esac case $(fdesetup status 2>/dev/null) in *"is On"*) fv=true ;; *"is Off"*) fv=false ;; esac case $(/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate 2>/dev/null) in *enabled*) fw=true ;; *disabled*) fw=false ;; esac # Last macOS update, from the system install history. local upd=$(plutil -convert xml1 -o - /Library/Receipts/InstallHistory.plist 2>/dev/null | awk ' // { d = ""; n = "" } /date<\/key>/ { getline; gsub(/.*|<\/date>.*/, ""); d = $0 } /displayName<\/key>/ { getline; gsub(/.*|<\/string>.*/, ""); n = $0 } /<\/dict>/ { if (n ~ /^macOS / && d > best) best = d } END { print best }') print -r -- "{\"v\":1,\"os\":\"macos\",\"agent\":\"$VERSION\",\ \"device\":{\"maker\":\"Apple\",\"model\":$(jstr $model),\"serial\":$(jstr $serial),\"type\":\"$dtype\"},\ \"system\":{\"name\":\"macOS\",\"version\":$(jstr $os_ver),\"release\":$(jstr $os_build),\"uptimeHours\":$(jnum $uptime_h)},\ \"cpu\":$(jstr $cpu),\"ram\":{\"totalGb\":$(jnum $ram_gb)},\ \"disks\":[${(j:,:)disks}],\ \"volumes\":[{\"mount\":\"/\",\"sizeGb\":$(jnum $vol_size),\"freeGb\":$(jnum $vol_free),\"system\":true}],\ \"battery\":$battery,\ \"backup\":{\"kind\":\"time_machine\",\"configured\":$(jbool $tm_conf),\"lastAt\":$(jstr $tm_last)},\ \"security\":{\"gatekeeper\":$(jbool $gk),\"encrypted\":$(jbool $fv),\"firewall\":$(jbool $fw)},\ \"updates\":{\"lastAt\":$(jstr $upd)}}" } # --- Send ----------------------------------------------------------------- check_args() { [[ $TOKEN =~ '^pl_[A-Za-z0-9_-]{43}$' ]] || die "the token is missing or malformed" # The token travels only over HTTPS; plain http is allowed for local testing only. [[ $ENDPOINT == https://* || $ENDPOINT == http://127.0.0.1:* || $ENDPOINT == http://localhost:* ]] || die "the server address must start with https://" } log_line() { [[ -d $BASE_DIR && $EUID -eq 0 ]] || return 0 print -r -- "$(date -u +%Y-%m-%dT%H:%M:%SZ) $*" >> "$BASE_DIR/agent.log" tail -n 200 "$BASE_DIR/agent.log" > "$TMP/log" && cat "$TMP/log" > "$BASE_DIR/agent.log" } send() { check_args collect > $TMP/report.json || die "could not read the system state" # The token goes in a curl config file, not on the command line, so that # other users of this Mac cannot see it in the process list. ( umask 077; print -r -- "header = \"Authorization: Bearer $TOKEN\"" > $TMP/curl.cfg ) local code code=$(curl -sS -K $TMP/curl.cfg -o $TMP/resp -w '%{http_code}' --max-time 40 \ -H 'Content-Type: application/json' --data-binary @$TMP/report.json -X POST "$ENDPOINT" 2>$TMP/err) || code=000 case $code in 200) log_line "sent"; print -r -- "ProfiLab Health: report sent." ;; 403) log_line "disabled by ProfiLab"; print -r -- "ProfiLab Health: watching is turned off for this Mac."; return 1 ;; 401) log_line "token not accepted"; print -r -- "ProfiLab Health: the token was not accepted (HTTP 401)."; return 1 ;; 429) log_line "too many reports, will try later"; print -r -- "ProfiLab Health: too many reports today, the next one will go later."; return 0 ;; *) log_line "not sent (HTTP $code)"; print -r -- "ProfiLab Health: report not sent (HTTP $code) $(head -c 200 $TMP/err 2>/dev/null)"; return 1 ;; esac } read_config() { local f="$BASE_DIR/config" line [[ -r $f ]] || return 1 # Read key=value lines; never source the file. while IFS= read -r line; do case $line in TOKEN=*) [[ -z $TOKEN ]] && TOKEN=${line#TOKEN=} ;; ENDPOINT=*) [[ -z $ENDPOINT ]] && ENDPOINT=${line#ENDPOINT=} ;; esac done < $f } # --- Install / uninstall ---------------------------------------------------- do_install() { [[ $EUID -eq 0 ]] || die "run it as administrator: sudo zsh $SELF --install " [[ -z $ENDPOINT ]] && ENDPOINT=$DEFAULT_ENDPOINT check_args mkdir -p "$BASE_DIR" || die "cannot create $BASE_DIR" chown root:wheel "$BASE_DIR" && chmod 755 "$BASE_DIR" if [[ $SELF != "$BASE_DIR/profilab-health.sh" ]]; then cp "$SELF" "$BASE_DIR/profilab-health.sh" || die "cannot copy the script" fi chown root:wheel "$BASE_DIR/profilab-health.sh" && chmod 755 "$BASE_DIR/profilab-health.sh" ( umask 077; printf 'TOKEN=%s\nENDPOINT=%s\n' "$TOKEN" "$ENDPOINT" > "$BASE_DIR/config" ) chown root:wheel "$BASE_DIR/config" && chmod 600 "$BASE_DIR/config" # Daily at 12:xx (a random minute spreads the load) and at every start-up. # If the Mac sleeps at that time, launchd runs the job when it wakes up. cat > $PLIST < Label$LABEL ProgramArguments /bin/zsh $BASE_DIR/profilab-health.sh RunAtLoad StartCalendarInterval Hour12Minute$(( RANDOM % 60 )) ProcessTypeBackground LowPriorityIO Nice10 EOF chown root:wheel $PLIST && chmod 644 $PLIST launchctl bootout system/$LABEL 2>/dev/null launchctl bootstrap system $PLIST 2>/dev/null || launchctl load -w $PLIST 2>/dev/null || die "launchd did not accept the job" print -r -- "ProfiLab Health: installed in $BASE_DIR (daily and at start-up)." # launchd starts the first run right away (RunAtLoad): wait for its result. local n=0 while (( n < 45 )) && [[ ! -s $BASE_DIR/agent.log ]]; do sleep 1; (( n++ )); done if [[ -s $BASE_DIR/agent.log ]]; then print -r -- "First report: $(tail -n 1 $BASE_DIR/agent.log)" else print -r -- "The first report will be sent in a minute." fi } do_uninstall() { [[ $EUID -eq 0 ]] || die "run it as administrator: sudo zsh \"$BASE_DIR/profilab-health.sh\" --uninstall" launchctl bootout system/$LABEL 2>/dev/null || launchctl unload $PLIST 2>/dev/null rm -f $PLIST rm -rf "$BASE_DIR" rmdir "/Library/Application Support/ProfiLab" 2>/dev/null print -r -- "ProfiLab Health: removed. Nothing is sent any more." } case $MODE in dry) collect ;; install) do_install ;; uninstall) do_uninstall ;; send) read_config [[ -z $ENDPOINT ]] && ENDPOINT=$DEFAULT_ENDPOINT send ;; esac