Launch Agent Help

jhbush
Valued Contributor II

I'm trying to get this script to run on a schedule of some sort as a launch agent. It keeps failing as an exit code 1. Hopefully someone knows what I'm doing wrong.

#!/bin/bash

# Logfile
LOGFILE="/Library/Logs/ClientEnroll.log"

#Get the MAC Address of the machine
MAC=$( networksetup -getmacaddress en0 | awk '{ print $3 }' | sed 's/:/./g' )

echo "$MAC" >> $LOGFILE

#Gather information from the JSS
JSSGroups=$( curl -s -u svc_account:password https://jss.mydomain.com:8443/JSSResource/computers/macaddress/$MAC 
| xpath //computer/groups_accounts/computer_group_memberships[1] 
| sed -e 's/<computer_group_memberships>//g;s/</computer_group_memberships>//g;s/<group>//g;s/</group>/
/g' )

#Show the groups the machine belongs to
echo "$JSSGroups"

#Check if the machine is enrolled in the JSS and enroll if needed
CheckMachine=`echo "$JSSGroups" | grep "All Managed Clients"`
    if [ "$CheckMachine" != "" ]; then
    echo "Machine is enrolled" >> $LOGFILE
    else
    echo "Machine is not enrolled...running QuickAdd.pkg" >> $LOGFILE
    /usr/sbin/installer -pkg /Library/Enroll/QuickAdd.pkg -target / >> $LOGFILE

    fi
4 REPLIES 4

stevewood
Honored Contributor II
Honored Contributor II

LaunchAgent or LaunchDaemon? If you're doing this as an agent, it might be failing due to privileges. LaunchAgents run as the logged in user, and since you're trying to install software that may not work.

You could try putting some error code statements throughout to debug where it is failing. Or some other echo statement just to figure out where the 1 is coming from.

mm2270
Legendary Contributor III

You can add 2 keys to your launchd job, StandardErrorPath and StandardOutPath with strings for each pointing to a log file it should write to. That will help troubleshooting where problems are occurring. Something like this:

<key>StandardErrorPath</key>
<string>/Library/Application Support/MyProcess/log.stderr</string>
<key>StandardOutPath</key>
<string>/Library/Application Support/MyProcess/log.stdout</string>

As @stevewood mentions though, if you are running this as an agent, it could be getting tripped up on the install QuickAdd part of the script.

Also, what are the permissions for both the script and the launchd job? I've found, as others have, that the permissions on these are important for making them work.

jhbush
Valued Contributor II

It appears I need to run it as LaunchDaemon. I moved my script to /usr/local/bin and called it from the daemon. I imagine someone else has done what I'm trying do so I hope someone posts some other ways to accomplish this.

franton
Valued Contributor III

Yes, making it a LaunchDaemon is the way to go. Only other tip is to make sure the script file is owned by root:wheel. It can be picky over file ownership.