-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAPI_Delete_Duplicate_Macs.sh
More file actions
285 lines (240 loc) · 9.55 KB
/
API_Delete_Duplicate_Macs.sh
File metadata and controls
285 lines (240 loc) · 9.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
#!/bin/bash
export PATH=/opt/homebrew/bin:$PATH
#####################################################################
# HISTORY
# 2024 08 02 Initial public commit
##################################################################################################################
# MAIN VARIABLES
SECONDS=0
OLDIFS=$IFS
IFS=','
STAMP=$(date +%Y%m%d-%H%M)
duplicatesFile="/var/log/OMC-JAMF-DUPLICATES-CLEANUP-$STAMP.csv"
working="/tmp/JAMF_DUPES"
currentUser=$( echo "show State:/Users/ConsoleUser" | scutil | awk '/Name :/ && ! /loginwindow/ { print $3 }' )
# SET TO NO FOR LIVE RUNS. This can be set in Jamf policy.
#DRYRUN="YES"
DRYRUN="${4:-"YES"}"
# API user and password UN-HASH FOR JAMF. This can be set in Jamf policy.
cryptedUser="${10}"
cryptedPass="${11}"
function DecryptString() {
echo "${1}" | /usr/bin/openssl enc -aes256 -md md5 -d -a -A -S "${2}" -k "${3}"
}
apiUser=$(DecryptString "${cryptedUser}" 'PASSWORD TO BE SALTED' 'PASSWORD TO BE SALTED' )
apiPass=$(DecryptString "${cryptedPass}" 'PASSWORD TO BE SALTED' 'PASSWORD TO BE SALTED' )
# Or just put creds in plain text. They're needed to create api tokens.
# For this we are using the same user and password on both servers.
apiUser="robert_redford"
apiPass="seTecaStronoMy"
# Email address for reporting. This is me. Hello!
reportEMAIL="markkenny@gmail.com"
#####################################################################
# Functions
function setUp () {
echo ""
echo "Jamf Duplicates Delete"
echo "Dryrun: $DRYRUN on $STAMP"
echo ""
if [[ -d "$working" ]]; then
rm -rf $working/*
else
mkdir -p $working
fi
cd $working
if [[ -f "$duplicatesFile" ]]; then
rm $duplicatesFile
else
echo "Create Duplicates CSV log file: $duplicatesFile"
echo "Serial_Number,Computer_Name,OLD_JSSID,OLD_Last_Enrollment,OLD_JAMF_SERVER,NEW_JSSID,NEW_Last_Enrollment,NEW_JAMF_SERVER" > $duplicatesFile
fi
requiredBinaries=("xmlstarlet")
for binary in "${requiredBinaries[@]}"; do
if command -v "$binary" > /dev/null; then
version=$( "$binary" --version | head -n 1)
echo "$binary is installed. Version: $version"
else
echo "$binary is not installed."
exit 1
fi
done
}
# Report ID on each server is an advanced search that has no criteria, this will report all Macs, managed and unmanged.
# Display Last Enrollment, Serial Number. (I have OS version, Username, cannot remember why, I thought it would be useful.)
function selectONE() {
echo "Setting ONE Server"
jssURL="https://one.jamf.company.com"
reportID="123"
server="ONE"
}
function selectTWO() {
echo "Setting TWO Server"
jssURL="https://TWO.jamf.company.com"
reportID="456"
server="TWO"
}
function downloadXML () {
echo "Download $server Advanced Search"
curl -H "Accept: text/xml" -sfk -H "Authorization: Bearer $token" ${jssURL}/JSSResource/advancedcomputersearches/id/${reportID} -X GET > $working/tmp_$server.xml
xmllint --format $working/tmp_$server.xml > $working/$server.xml
}
function reportEmail () {
reportFile=$( cat $duplicatesFile | cut -d ',' -f 1,5 | tail -n+2 | sort -k2 -t, > $working/EMAIL_DUPLICATES_REPORT.csv )
reportFile="$working/EMAIL_DUPLICATES_REPORT.csv"
dupeCount=$(($(wc -l < "$reportFile") ))
MESSAGE=$( cat ${reportFile} )
if [ $DRYRUN == "YES" ]; then
emailSubject="DRY-RUN Jamf Duplicates Deleted: $dupeCount"
sudo -u "$currentUser" echo "$MESSAGE" | mail -s "${emailSubject}" "${reportEMAIL}"
else
emailSubject="Jamf Duplicates Deleted: $dupeCount"
sudo -u "$currentUser" echo "$MESSAGE" | mail -s "${emailSubject}" "${reportEMAIL}"
fi
}
findOldestSN() {
local serial=$1
echo "Checking Duplicate serial number: $serial"
local TWO_entry=$(/opt/homebrew/bin/xmlstarlet sel -T -t -m "/advanced_computer_search/computers/computer[Serial_Number='$serial']" \
-v "Serial_Number" -o "," \
-v "Computer_Name" -o "," \
-v "id" -o "," \
-v "Last_Enrollment" -o ",TWO" -n TWO.xml | sort -t',' -k4,4 | head -n 1)
echo $TWO_entry
local ONE_entry=$(/opt/homebrew/bin/xmlstarlet sel -T -t -m "/advanced_computer_search/computers/computer[Serial_Number='$serial']" \
-v "Serial_Number" -o "," \
-v "Computer_Name" -o "," \
-v "id" -o "," \
-v "Last_Enrollment" -o ",ONE" -n ONE.xml | sort -t',' -k4,4 | head -n 1)
echo $ONE_entry
if [[ -n "$TWO_entry" && -n "$ONE_entry" ]]; then
local newer_jss_id_TWO=$(cut -d',' -f3 <<<"$TWO_entry")
local newer_last_enrollment_TWO=$(cut -d',' -f4 <<<"$TWO_entry")
local newer_file_TWO="TWO"
local newer_jss_id_ONE=$(cut -d',' -f3 <<<"$ONE_entry")
local newer_last_enrollment_ONE=$(cut -d',' -f4 <<<"$ONE_entry")
local newer_file_ONE="ONE"
local timestamp_TWO=$(date -jf "%Y-%m-%d %H:%M:%S" "$newer_last_enrollment_TWO" "+%s")
local timestamp_ONE=$(date -jf "%Y-%m-%d %H:%M:%S" "$newer_last_enrollment_ONE" "+%s")
if [[ "$timestamp_TWO" -lt "$timestamp_ONE" ]]; then
echo "$TWO_entry,$newer_jss_id_ONE,$newer_last_enrollment_ONE,$newer_file_ONE" >> "$duplicatesFile"
else
echo "$ONE_entry,$newer_jss_id_TWO,$newer_last_enrollment_TWO,$newer_file_TWO" >> "$duplicatesFile"
fi
elif [ -n "$TWO_entry" ]; then
echo "$TWO_entry,,,,," >> "$duplicatesFile"
elif [ -n "$ONE_entry" ]; then
echo "$ONE_entry,,,,," >> "$duplicatesFile"
fi
}
processSN() {
echo "Process Duplicate serial numbers"
unique_serial_numbers=$(comm -12 <(/opt/homebrew/bin/xmlstarlet sel -T -t -m "/advanced_computer_search/computers/computer" -v "Serial_Number" -n TWO.xml | sort -u) \
<(/opt/homebrew/bin/xmlstarlet sel -T -t -m "/advanced_computer_search/computers/computer" -v "Serial_Number" -n ONE.xml | sort -u) | paste -sd "," -)
echo "$unique_serial_numbers," | tr ',' '\n' | while read -r serial; do
findOldestSN "$serial"
done
awk -F',' 'BEGIN {
print "OLD_JSSID,Serial_Number,Computer_Name" > "TWO_DELETE.csv"
print "OLD_JSSID,Serial_Number,Computer_Name" > "ONE_DELETE.csv"
}
NR > 1 {
if ($5 == "TWO" || $5 == "\"TWO\"" || $5 == "ONE" || $5 == "\"ONE\"") {
print $3 "," $1 "," $2 >> ($5 == "TWO" || $5 == "\"TWO\"" ? "TWO_DELETE.csv" : "ONE_DELETE.csv")
}
}' "${duplicatesFile}"
}
deleteTWOids() {
TWO_IDs=$(cut -d',' -f1 TWO_DELETE.csv | sed '1d' | paste -sd ',' -)
if [ "$TWO_IDs" ]; then
echo "IDs of duplicate Macs in TWO to Delete..."
echo "$TWO_IDs"
jamfproIDURL="${jssURL}/JSSResource/computers/id"
for ID in $TWO_IDs; do
if [[ "$ID" =~ ^[0-9]+$ ]]; then
if [ $DRYRUN == "YES" ]; then
echo "DRY-RUN Delete ${jamfproIDURL}/$ID"
else
echo "DELETING ${jamfproIDURL}/$ID"
curl -sk -H "Authorization: Bearer $token" "${jamfproIDURL}/$ID" -X DELETE
fi
else
echo "The following input is not a number: $ID"
fi
done
else
echo "No duplicate Macs in TWO to Delete"
echo ""
fi
}
deleteONEids() {
ONE_IDs=$(cut -d',' -f1 ONE_DELETE.csv | sed '1d' | paste -sd ',' -)
if [ "$ONE_IDs" ]; then
echo "IDs of duplicate Macs in ONE to Delete..."
echo "$ONE_IDs"
jamfproIDURL="${jssURL}/JSSResource/computers/id"
for ID in $ONE_IDs; do
if [[ "$ID" =~ ^[0-9]+$ ]]; then
if [ $DRYRUN == "YES" ]; then
echo "DRY-RUN Delete ${jamfproIDURL}/$ID"
else
echo "DELETING ${jamfproIDURL}/$ID"
curl -sk -H "Authorization: Bearer $token" "${jamfproIDURL}/$ID" -X DELETE
fi
else
echo "The following input is not a number: $ID"
fi
done
else
echo "No duplicate Macs in ONE to Delete"
fi
}
# # Tokens # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
requestAuthToken() {
authToken=$( /usr/bin/curl -X POST -s "$jssURL/api/v1/auth/token" -u "$apiUser:$apiPass" )
token=$( /usr/bin/plutil -extract token raw - <<< "$authToken" )
tokenExpiration=$( /usr/bin/plutil -extract expires raw - <<< "$authToken" )
localTokenExpirationEpoch=$( TZ=GMT /bin/date -j -f "%Y-%m-%dT%T" "$tokenExpiration" +"%s" 2> /dev/null )
}
verifyToken() {
checkToken=$( /usr/bin/curl -s "$jssURL/api/v1/auth" -H "Authorization: Bearer $token" --write-out "%{http_code}" )
tokenStatus=${checkToken: -3}
}
renewToken() {
authToken=$( /usr/bin/curl -X POST -s "$jssURL/api/v1/auth/keep-alive" -H "Accept: application/json" -H "Authorization: Bearer $token" )
token=$( /usr/bin/plutil -extract token raw - <<< "$authToken" )
tokenExpiration=$( /usr/bin/plutil -extract expires raw - <<< "$authToken" )
localTokenExpirationEpoch=$( TZ=GMT /bin/date -j -f "%Y-%m-%dT%T" "$tokenExpiration" +"%s" 2> /dev/null )
renewalTime=$(( $localTokenExpirationEpoch - 300 ))
}
expireAuthToken() {
/usr/bin/curl -X POST -s "$jssURL/api/v1/auth/invalidate-token" -H "Authorization: Bearer $token"
token=""
}
#####################################################################
## Run the job!
setUp
selectONE
requestAuthToken
verifyToken
downloadXML
expireAuthToken
selectTWO
requestAuthToken
verifyToken
downloadXML
expireAuthToken
processSN
selectTWO
requestAuthToken
verifyToken
deleteTWOids
expireAuthToken
selectONE
requestAuthToken
verifyToken
deleteONEids
expireAuthToken
duration=$SECONDS
reportEmail
IFS=$OLDIFS
exit 0