Skip to content

Instantly share code, notes, and snippets.

@alecmeelan
Forked from talkingmoose/Location Information.zsh
Last active October 10, 2024 14:46
Show Gist options
  • Save alecmeelan/92a777e90106dff781db08b17297eafd to your computer and use it in GitHub Desktop.
Save alecmeelan/92a777e90106dff781db08b17297eafd to your computer and use it in GitHub Desktop.
Add the following script to a Jamf Pro extension attribute to collect service provider location information based on public IP address when updating inventory.
#!/bin/zsh
# Get public IP address
publicIP=$( /usr/bin/curl http://ifconfig.io/ip \
--location \
--silent \
--max-time 10 )
# Check if public IP was retrieved
if [[ -z "$publicIP" ]]; then
echo "<result>Unable to retrieve public IP address</result>"
exit 1
fi
# Get GeoIP data
locationData=$( /usr/bin/curl http://ip-api.com/xml/$publicIP \
--location \
--silent \
--max-time 10 )
# Check if location data was retrieved
if [[ -z "$locationData" ]]; then
echo "<result>Unable to retrieve GeoIP data</result>"
exit 1
fi
# Define array of desired location fields
locationPieces=( country countryCode region regionName city zip lat lon timezone isp org as )
# Loop through each field, parse value, and handle empty cases
result=""
for anItem in $locationPieces; do
value=$( /usr/bin/xmllint --xpath "string(/query/$anItem)" - <<< "$locationData" 2>/dev/null )
if [[ -z "$value" ]]; then
value="N/A" # Use "N/A" if value is missing
fi
result+="$anItem: $value\n"
done
# Output the results
echo -e "<result>$result</result>"
exit 0
@alecmeelan
Copy link
Author

Updated Script with Checks for Empty Values, Fallback Values for Missing Data, and updated the Formatted Output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment