API Extracting data, modifying it and Putting it back using loop

akamenev47
Contributor II

Hey guys,

I am still kinda new to API as well as loops in scripting and have been struggling writing out a script, which should should grab all computer names from the JSS via API, check if a computer name has "MM-MAC-" in front of it's name and if it does, grab everything after "MM-MAC-" and PUT it into the Asset Tag field on JSS via API.

I got the extraction of the needed stuff working (if not inside the loop) and the PUT command is also working fine, the issue I think is in my loop logic and how I extract data as it seems like all the data it takes from API is assigned/handled including ALL computer names instead of handling it 1 by 1. Any help will be greatly appreciated.

Here is the script:

#!/bin/bash

jssurl=JSSURL
user=ACCOUNT
pass=PASSWORD

for i in jsscomputername
do 
jsscomputername=`/usr/bin/curl -k -u $user:$pass "$jssurl/JSSResource/computers" | xmllint --format - | awk -F '[<>]' '/<name>/{print $3}'`

#Get ALL the chars after "MM-MAC-"
assettagextracted=${jsscomputername#*MM-MAC-}
#Get 7 first chars of the computer name to catch the "MM-MAC-"
computernamecheck=${jsscomputername:0:7}

#Check if computer name contains 'MM-MAC-' in the name and if it does, assigne everything after "MM-MAC-" to asset tag variable and PUT to JSS
if [[ $computernamecheck == "MM-MAC-" ]]
    then
        #Add the Asset Tag to JSS
        curl -ksu $user:$pass $jssurl/JSSResource/computers/name/$jsscomputername -H "Content-type: application/xml" -X PUT -d "<computer><general><asset_tag><value>$assettagextracted</value></asset_tag></general></computer>"
    else
        echo "Computer name does not meet the Asset Tag addition condition. No further action."
        exit 0
fi
Ahoy!
1 REPLY 1

anverhousseini
Contributor II

You can get the IDs of all computers like this:

#!/bin/bash

tmpFolder=$(getconf DARWIN_USER_CACHE_DIR) && randString=$(/usr/bin/openssl rand -hex 5) && workDir="${tmpFolder}${randString}" && /bin/mkdir -p "${workDir}"

jamfUsername="username"
jamfPassword="password"
jamfBaseURL="https://jamf.example.com"
jamfComputerResource="JSSResource/computers"

/usr/bin/curl -H "Accept: application/xml" -s -o "${workDir}/ComputersOutput.xml" -fku "${jamfUsername}":"${jamfPassword}" "${jamfBaseURL}/${jamfComputerResource}" -X GET

/usr/local/bin/xmlstarlet sel -t -v '/computers/computer/id/text()' "${workDir}/ComputersOutput.xml" > "${workDir}/ComputersIDList"

while read line && [ ! -z "${line}" ]; do
    echo "${jamfBaseURL}/JSSResource/computers/id/${line}"
done < "${workDir}/ComputersIDList"

rm -rf "${workDir}"