-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQuery1.py
169 lines (135 loc) · 5.31 KB
/
Query1.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
import os
import pandas as pd
import json
import smtplib, ssl, email
import pyodbc
from datetime import timedelta, datetime, timezone
from azure.monitor.query import LogsQueryClient, LogsBatchQuery, LogsQueryStatus
from azure.identity import DefaultAzureCredential, ClientSecretCredential
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
date = datetime.now().strftime("%Y_%m_%d")
server = 'tcp:' # Paste your DB IP address here
database = 'MicrosoftAAD' # Paste your DB Name that you created in DB here
username = '' # Paste the account that you will use to login and write date into here
password = '' # Paste the password that you will use to login and write date into here
#DB driver Definition from Python library
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
def __Convert__(string):
li = list(string.split(" "))
return li
TENANT_ID = ''
CLIENT_ID = ''
CLIENT_SECRET = '' # Client Secret
WORKSPACE_ID = '' # from the log analytics workspace
sender_email = "IT.Notifier@123.com"
receiver_email = "IT.Watchdog@123.com"
SMTP = "localhost"
credential = ClientSecretCredential(
client_id = CLIENT_ID,
client_secret = CLIENT_SECRET,
tenant_id = TENANT_ID
)
client = LogsQueryClient(credential)
query = (
"""AuditLogs
| where OperationName == "User registered security info"
"""
)
request = [
LogsBatchQuery(
query = query,
timespan = timedelta(days=1),
workspace_id = WORKSPACE_ID
),
]
results = client.query_batch(request)
for res in results:
if res.status == LogsQueryStatus.FAILURE:
# This will be a LogsQueryError
print(res)
elif res.status == LogsQueryStatus.PARTIAL:
# This will be a LogsQueryPartialResult
print(res.partial_error)
for table in res.partial_data:
df = pd.DataFrame(table.rows, columns=table.columns)
elif res.status == LogsQueryStatus.SUCCESS:
# This will be a LogsQueryResult
table = res.tables[0]
df = pd.DataFrame(table.rows, columns=table.columns)
output = df.to_dict(orient = 'records')
cursor = conn.cursor()
a = [value1['ResultDescription'] for value1 in output if 'ResultDescription' in value1]
b = userPrincipalName = [
json.loads(value2['InitiatedBy'])['user']['userPrincipalName']
for value2 in output if 'InitiatedBy' in value2
]
c = ipAddr = [
json.loads(value3['InitiatedBy'])['user']['ipAddress']
for value3 in output if 'InitiatedBy' in value3
]
d = [value4['LoggedByService'] for value4 in output if 'LoggedByService' in value4]
e = [value5['Result'] for value5 in output if 'Result' in value5]
f = [value6['ResultReason'] for value6 in output if 'ResultReason' in value6]
g = [value7['ActivityDisplayName'] for value7 in output if 'ActivityDisplayName' in value7]
h = [value8['ActivityDateTime'] for value8 in output if 'ActivityDateTime' in value8]
number_of_d = len(d)
print(number_of_d)
cursor.execute("DELETE FROM _2FA_Auditlog_")
z = -1
for a1 in a:
z+=1
b1 = b[z]
c1 = c[z]
d1 = d[z]
e1 = e[z]
f1 = f[z]
g1 = g[z]
h1 = h[z]
#Check the table names and column names are matched yours.
cursor.execute("INSERT INTO _2FA_Auditlog_ (ResultDescription, InitiatedBy, IPaddr, LoggedByService, Result, ResultReason, ActivityDisplayName, UTC) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", a1, b1, c1, d1, e1, f1, g1, h1)
output = cursor.execute("Select * FROM _2FA_Auditlog_")
output_html = """
<table border='1' cellpadding='5' cellspacing='0' style='font-family: Arial, sans-serif; font-size: 12px;'>
<tr>
<th style='font-size: 12px;'>ResultDescription</th>
<th style='font-size: 12px;'>InitiatedBy</th>
<th style='font-size: 12px;'>IP Address</th>
<th style='font-size: 12px;'>LoggedByService</th>
<th style='font-size: 12px;'>Result</th>
<th style='font-size: 12px;'>Result Reason</th>
<th style='font-size: 12px;'>ActivityDisplayName</th>
<th style='font-size: 12px;'>UTC</th>
</tr>
"""
for row in output:
output_html += "<tr>"
output_html += "".join([f"<td style='font-size: 12px;'>{str(item)}</td>" for item in row])
output_html += "</tr>"
output_html += "</table>"
# Insert the generated HTML into the email template
html = f"""
<html>
<body style='font-family: Arial, sans-serif; font-size: 10px;'>
<h2 style='font-size: 14px; font-weight: normal;'>Hello,</h2>
<h2 style='font-size: 14px; font-weight: normal;'>This is the daily digest of Advantech users' MFA activity from Microsoft Azure Active Directory, the list has also included global employees. You might check for your users if you see any atypical activities on their accounts. If you have any questions, please feel free to contact ANA.IT.Helpdesk@advantech.com.</h2>
<br></br>
{output_html}
</body>
</html>
"""
part = MIMEText(html, "html")
msg = MIMEMultipart("alternative")
msg["Subject"] = "Daily Digest of Advantech MFA Activity"
msg["From"] = sender_email
msg["To"] = receiver_email
#msg["X-Priority"] = '2'
msg.attach(part)
with smtplib.SMTP('localhost') as server:
server.sendmail(
sender_email, receiver_email, msg.as_string()
)
conn.commit()
cursor.close()