-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOnlyRemoving.py
191 lines (138 loc) · 6.46 KB
/
OnlyRemoving.py
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
#import csv
#import pyodbc
import json
import urllib.request
import urllib.parse
import urllib.error
import requests
import os
import re
from datetime import datetime
def __Convert__(string):
li = list(string.split(" "))
return li
tenantId = '' # Paste your own tenant ID here
appId = '' # Paste your own app ID here
appSecret = '' # Paste your own app secret here
date = datetime.now().strftime("%Y_%m_%d")
url = "https://login.microsoftonline.com/%s/oauth2/token" % (tenantId)
resourceAppIdUri = 'https://api.securitycenter.microsoft.com'
body = {
'resource': resourceAppIdUri,
'client_id': appId,
'client_secret': appSecret,
'grant_type': 'client_credentials'
}
data = urllib.parse.urlencode(body).encode("utf-8")
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
jsonResponse = json.loads(response.read())
aadToken = jsonResponse["access_token"]
#print(aadToken) #To Check the raw token value, for Debugging.
queryKQLRemoval = open(
r'C:\Users\ryanc\Documents\GitHub\MicrosoftDefender_BulkUpdateMachineInfo\OnlyRemoving\ListTargetMachineRemoval.txt') # To Open the AdvancedHunting script.
queryRemoval = queryKQLRemoval.read()
queryKQLRemoval.close()
url = "https://api.securitycenter.microsoft.com/api/advancedqueries/run"
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': "Bearer " + aadToken
}
data = json.dumps({ 'Query' : queryRemoval }).encode("utf-8")
reqToRemove = urllib.request.Request(url, data, headers)
responseToRemove = urllib.request.urlopen(reqToRemove)
jsonResponseForRemove = json.loads(responseToRemove.read())
schemaForRemove = jsonResponseForRemove["Schema"]
resultsForRemove = jsonResponseForRemove["Results"]
url = "https://api.securitycenter.microsoft.com/api/machines/AddOrRemoveTagForMultipleMachines"
# The Removing section begin from here.
print("------------ The removing job is starting -------------")
machineIdsValue = []
count = 0
Total = 0
for EveryEntry in resultsForRemove:
__Convert__(EveryEntry["DeviceId"])
if EveryEntry["DeviceId"] not in machineIdsValue:
machineIdsValue.append(EveryEntry["DeviceId"])
if len(machineIdsValue) == 495:
body = {
"Value" : "ARD",
"Action" : "Remove",
"MachineIds" : machineIdsValue
}
try:
data = json.dumps(body).encode("utf-8")
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
jsonResponse = json.loads(response.read())
count = count+1
print("The length of entries has reached the 495 limit. The removing job is performing the", count, "Times...")
Total = Total + len(machineIdsValue)
machineIdsValue.clear()
except urllib.error.HTTPError as err:
if err.code == 400:
json_container = json.loads(str(err.read(), 'utf-8'))
dictGet = json_container["error"]["message"]
dictSplit = dictGet.split()
dictSplit2 = str(dictSplit)
mixed_string = re.findall(r'\b\w+\b', dictSplit2)
subset = mixed_string[4:]
for errorEntry in subset:
if errorEntry in machineIdsValue:
machineIdsValue.remove(errorEntry)
body = {
"Value" : "ARD",
"Action" : "Remove",
"MachineIds" : machineIdsValue
}
data = json.dumps(body).encode("utf-8")
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
jsonResponse = json.loads(response.read())
count = count+1
print("The length is", len(machineIdsValue), "after error handling. The removing job is performing the", count, "Times...")
Total = Total + len(machineIdsValue)
machineIdsValue.clear()
if len(machineIdsValue) == 0:
print ("The length is zero..., ending the removing job")
else:
try:
body = {
"Value" : "ARD",
"Action" : "Remove",
"MachineIds" : machineIdsValue
}
data = json.dumps(body).encode("utf-8")
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
jsonResponse = json.loads(response.read())
count = count+1
print("The length is", len(machineIdsValue), ". The removing job is performing the", count, "Times...")
Total = Total + len(machineIdsValue)
machineIdsValue.clear()
except urllib.error.HTTPError as err:
if err.code == 400:
json_container = json.loads(str(err.read(), 'utf-8'))
dictGet = json_container["error"]["message"]
dictSplit = dictGet.split()
dictSplit2 = str(dictSplit)
mixed_string = re.findall(r'\b\w+\b', dictSplit2)
subset = mixed_string[4:]
for errorEntry in subset:
if errorEntry in machineIdsValue:
machineIdsValue.remove(errorEntry)
body = {
"Value" : "ARD",
"Action" : "Remove",
"MachineIds" : machineIdsValue
}
data = json.dumps(body).encode("utf-8")
req = urllib.request.Request(url, data, headers)
response = urllib.request.urlopen(req)
jsonResponse = json.loads(response.read())
count = count+1
print("The length is", len(machineIdsValue), "after error handling. The removing job is performing the", count, "Times...")
Total = Total + len(machineIdsValue)
machineIdsValue.clear()
print("The total length of removing is", Total)