-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathupdateUsers.py
More file actions
490 lines (403 loc) · 15.2 KB
/
updateUsers.py
File metadata and controls
490 lines (403 loc) · 15.2 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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
#-------------------------------------------------------------------------------
# Name: Portal User Management
# Purpose: This script will auto manage accounts in the system that are tied to
# to the enterprise IDP. If a user account is not present or
# disabled, it will disable the account. If the account is present
# and enabled, it will ensure the system has the account enabled.
#
# Author: John Spence
#
# Created: 2022-09-01
# Modified: 2022-09-28
# Modification Purpose: Added in support for Portal.
#
#
#-------------------------------------------------------------------------------
# 888888888888888888888888888888888888888888888888888888888888888888888888888888
# ------------------------------- Configuration --------------------------------
#
# ------------------------------- Dependencies ---------------------------------
#
# 888888888888888888888888888888888888888888888888888888888888888888888888888888
# Portal Config
portalURL = 'https://www.arcgis.com/' #your AGOL URL
portalUSR = '' #your AGOL user name
portalPAS = '' #your AGOL password (base64 encoded // Security through obscurity :P )
# Script Type
scriptType = 'AGOL User Management'
# ADFS Config
adfsServer = 'subdomain.domain.com'
adfsRootDomain = 'subdomain.domain.com'
ldapUSR = r'' #User Name
ldapPAS = '' #(base64 encoded // Security through obscurity :P )
# Send confirmation of rebuild to
adminNotify = 'gisadmin@domain.com'
deptAdminNotify = 'info@domain.com'
# Configure the e-mail server and other info here.
mail_server = 'smtprelay.domain.com'
mail_from = '{} <noreply@domain.com>'.format(scriptType)
mail_subject = '{} Automated Actions Notification'.format(scriptType)
# Test User Override
testUser = ''
# ------------------------------------------------------------------------------
# DO NOT UPDATE BELOW THIS LINE OR RISK DOOM AND DISPAIR! Have a nice day!
# ------------------------------------------------------------------------------
# Import Python libraries
import arcpy
import arcgis
from arcgis.gis import GIS
import base64
import datetime
import time
import urllib
import requests
import json
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import concurrent.futures
import ldap3
from ldap3 import Server, Connection, ALL
#-------------------------------------------------------------------------------
#
#
# Functions
#
#
#-------------------------------------------------------------------------------
def main():
#-------------------------------------------------------------------------------
# Name: Function - main
# Purpose: Starts the whole thing.
#-------------------------------------------------------------------------------
starttime = datetime.datetime.now()
portalCheck = signinPortal(starttime)
usersEnabled, usersDisabled, usersDisabledAlready = getPortalUsers(portalCheck)
sendNotification(usersEnabled, usersDisabled, usersDisabledAlready)
return
def signinPortal(starttime):
#-------------------------------------------------------------------------------
# Name: Function - signinPortal
# Purpose: Signs into Portal
#-------------------------------------------------------------------------------
portalInfo = arcpy.SignInToPortal(portalURL, portalUSR, base64.b64decode(portalPAS))
portalDesc = arcpy.GetPortalDescription()
portalID = portalDesc['id']
print ('\nStartup : {}\n'.format(starttime))
print ('******** Portal Check Completed ******** ')
if portalID == '0123456789ABCDEF':
print (' - Portal connection: Internal Portal')
portalCheck = 1
else:
print (' - Portal connection: ArcGIS Online')
portalCheck = 0
print ('\n\n')
return(portalCheck)
def ldapCheck(portalUserCheck, portalCheck):
#-------------------------------------------------------------------------------
# Name: Function - ldapCheck
# Purpose:
#-------------------------------------------------------------------------------
conn = Connection(Server('LDAP://{}'.format(adfsServer)), auto_bind = True, user = ldapUSR, password = base64.b64decode(ldapPAS))
if portalCheck != 0:
conn.search('dc=subdomain,dc=domain,dc=com', '(&(objectclass=person)(SamAccountName={}))'.format(portalUserCheck), attributes=['Name', 'Department', 'SamAccountName', 'UserPrincipalName', 'userAccountControl'])
else:
conn.search('dc=subdomain,dc=domain,dc=com', '(&(objectclass=person)(UserPrincipalName={}))'.format(portalUserCheck), attributes=['Name', 'Department', 'SamAccountName', 'UserPrincipalName', 'userAccountControl'])
respCode = 0
if len (conn.entries) != 0:
results = conn.entries[0]
portalUser = results.Name
portalUserDept = results.Department
portalUserSAM = results.SamAccountName
portalUserUPN = results.UserPrincipalName
print (' -- Domain User exists')
print (' -- Department: {}'.format(portalUserDept))
print (' -- SAM Account: {}'.format(portalUserSAM))
if results.userAccountControl == 514:
respCode = 1
print (' -- WARNING: This account is disabled in the domain.')
else:
print (' !! ERROR - DOMAIN USER DOES NOT EXIST')
portalUserDept = None
respCode = 1
return (portalUserDept, respCode)
def getPortalUsers(portalCheck):
#-------------------------------------------------------------------------------
# Name: Function - getPortalUsers
# Purpose:
#-------------------------------------------------------------------------------
usersEnabled = []
usersDisabled = []
usersDisabledAlready = []
gis = GIS('Home')
totalUsers = gis.users.counts('user_type', as_df=False)[0]['count']
users = gis.users.search (query='', max_users=10000)
for i in users:
if i.idpUsername != None:
try:
print(i.fullName, ' | ', i.idpUsername, ' | ', i.categories, ' | ', i.disabled)
except:
print(i.fullName, ' | ', i.idpUsername, ' | N/A | ', i.disabled)
portalUserCheck = i.idpUsername.lower()
portalUserDept, respCode = ldapCheck(portalUserCheck, portalCheck)
if respCode == 1 and i.disabled != True:
userID = i.username
print (' -- Update action: DISABLING USER ACCOUNT')
if testUser != '':
print (' -- Fake Disable...')
else:
gis.users.disable_users([userID])
payload = (i.fullName, i.idpUsername, portalUserDept, 'AD user disabled or not found. Account Disabled.', 'Check for content, transfer training when applicable, and delete user.')
usersDisabled.append(payload)
print ('\n\n')
elif respCode == 1 and i.disabled == True:
print (' -- Update action: None Required. Account Disabled')
payload = (i.fullName, i.idpUsername, portalUserDept, 'No action required. Account already disabled.', 'May be seasonal worker. Check with department.')
usersDisabledAlready.append(payload)
print ('\n\n')
elif respCode != 1 and i.disabled == True:
userID = i.username
print (' -- Update action: Account Enabled')
if testUser != '':
print (' -- Fake Enable...')
else:
gis.users.enable_users([userID])
payload = (i.fullName, i.idpUsername, portalUserDept, 'AD user account found. Account Enabled.', 'No action required.')
usersEnabled.append(payload)
print ('\n\n')
else:
print (' -- Update action: None Required. Domain and Account active.')
print ('\n\n')
return (usersEnabled, usersDisabled, usersDisabledAlready)
def sendNotification(usersEnabled, usersDisabled, usersDisabledAlready):
UErowOutput = ''
if len(usersEnabled) != 0:
for ue in usersEnabled:
ueuserFullName = ue[0]
ueuseridpUsername = ue[1]
ueuserDept = ue[2]
ueuserAction = ue[3]
ueuserRecommendedAction = ue[4]
print (ueuserFullName, ' ', ueuseridpUsername, ' ', ueuserDept, ' ', ueuserAction)
rowLine = '''
<tr>
<td>{}</td>
<td>{}</td>
<td>{}</td>
<td>{}</td>
<td>{}</td>
</tr>
'''.format(ueuserFullName, ueuseridpUsername, ueuserDept, ueuserAction, ueuserRecommendedAction)
UErowOutput = UErowOutput + rowLine
ueNotification = 1
else:
print ('No Notification Required.')
ueNotification = 0
UDrowOutput = ''
if len(usersDisabled) != 0:
for ud in usersDisabled:
uduserFullName = ud[0]
uduseridpUsername = ud[1]
uduserDept = ud[2]
uduserAction = ud[3]
uduserRecommendedAction = ud[4]
print (uduserFullName, ' ', uduseridpUsername, ' ', uduserDept, ' ', uduserAction)
rowLine = '''
<tr>
<td>{}</td>
<td>{}</td>
<td>{}</td>
<td>{}</td>
<td>{}</td>
</tr>
'''.format(uduserFullName, uduseridpUsername, uduserDept, uduserAction, uduserRecommendedAction)
UDrowOutput = UDrowOutput + rowLine
udNotification = 1
else:
print ('No Notification Required.')
udNotification = 0
UArowOutput = ''
if len(usersDisabledAlready) != 0:
for uad in usersDisabledAlready:
uaduserFullName = uad[0]
uaduseridpUsername = uad[1]
uaduserDept = uad[2]
uaduserAction = uad[3]
uaduserRecommendedAction = uad[4]
print (uaduserFullName, ' ', uaduseridpUsername, ' ', uaduserDept, ' ', uaduserAction)
rowLine = '''
<tr>
<td>{}</td>
<td>{}</td>
<td>{}</td>
<td>{}</td>
<td>{}</td>
</tr>
'''.format(uaduserFullName, uaduseridpUsername, uaduserDept, uaduserAction, uaduserRecommendedAction)
UArowOutput = UArowOutput + rowLine
uadNotification = 1
else:
print ('No Notification Required.')
uadNotification = 0
if (ueNotification == 1 or udNotification == 1) and uadNotification == 1:
print ('\nPreparing notification...')
else:
print ('\nNo notification required to be sent. Script terminating.')
UEpayLoadHTMLStart = '''
<div>
<h3 style="font-family:verdana;">Accounts Enabled</h3>
<table>
<tr>
<th>User</th>
<th>IDP UserID</th>
<th>Department</th>
<th>Auto Actions Taken</th>
<th>Recommended Manual Actions</th>
</tr>
'''
if len(usersEnabled) != 0:
UEpayLoadHTMLData = '''
{}
</table>
</div>
<br>
'''.format(UErowOutput)
else:
UEpayLoadHTMLData = '''
</table>
<h5 style="font-family:verdana;"><center>No accounts were enabled</center></h5>
</div>
<br>
'''
UEpayLoadHTML = UEpayLoadHTMLStart + UEpayLoadHTMLData
UDpayLoadHTMLStart = '''
<div>
<h3 style="font-family:verdana;">Accounts Disabled</h3>
<table>
<tr>
<th>User</th>
<th>IDP UserID</th>
<th>Department</th>
<th>Auto Actions Taken</th>
<th>Recommended Manual Actions</th>
</tr>
'''
if len(usersDisabled) != 0:
UDpayLoadHTMLData = '''
{}
</table>
</div>
<br>
'''.format(UDrowOutput)
else:
UDpayLoadHTMLData = '''
</table>
<h5 style="font-family:verdana;"><center>No accounts were disabled</center></h5>
</div>
<br>
'''
UDpayLoadHTML = UDpayLoadHTMLStart + UDpayLoadHTMLData
UApayLoadHTMLStart = '''
<div>
<h3 style="font-family:verdana;">Previous Accounts Disabled</h3>
<table>
<tr>
<th>User</th>
<th>IDP UserID</th>
<th>Department</th>
<th>Auto Actions Taken</th>
<th>Recommended Manual Actions</th>
</tr>
'''
if len(usersDisabledAlready) != 0:
UApayLoadHTMLData = '''
{}
</table>
</div>
<br>
'''.format(UArowOutput)
else:
UApayLoadHTMLData = '''
</table>
<h5 style="font-family:verdana;"><center>No accounts were disabled</center></h5>
</div>
<br>
'''
UApayLoadHTML = UApayLoadHTMLStart + UApayLoadHTMLData
payLoadHTMLStart = '''
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<h2 style="font-family:verdana;"><b>User Management Actions</b></h2>
'''
payLoadHTMLEnd = '''
<br>
<div>
<bold>*Seasonal worker accounts will auto enable when AD user account is enabled.</bold>
</div>
<div>
[This is an automated system message. Please contact gisdba@bellevuewa.gov for all questions.]
</div>
</body>
</html>
'''
payLoadHTML = payLoadHTMLStart + UDpayLoadHTML + UEpayLoadHTML + UApayLoadHTML + payLoadHTMLEnd
payLoadTXT = 'HTML Message -- Use HTML Compliant Email'
partTXT = MIMEText(payLoadTXT, 'plain')
partHTML = MIMEText(payLoadHTML, 'html')
msg = MIMEMultipart('alternative')
msg['Subject'] = mail_subject
msg['From'] = mail_from
msg['X-Priority'] = '5' # 1 high, 3 normal, 5 low
if testUser != '':
if ueNotification != 0 or udNotification != 0:
emailContact = testUser
print ('Sending data to {}'.format(emailContact))
msg['To'] = emailContact
msg.attach(partTXT)
msg.attach(partHTML)
server = smtplib.SMTP(mail_server)
server.sendmail(mail_from, [emailContact], msg.as_string())
server.quit()
else:
print ('No notifications required.')
else:
if ueNotification != 0 or udNotification != 0:
emailContact = deptAdminNotify
print ('Sending data to {}'.format(emailContact))
msg['To'] = emailContact
msg['Cc'] = adminNotify
msg.attach(partTXT)
msg.attach(partHTML)
server = smtplib.SMTP(mail_server)
server.sendmail(mail_from, [emailContact, adminNotify], msg.as_string())
server.quit()
else:
print ('No notifications required.')
return
#-------------------------------------------------------------------------------
#
#
# MAIN SCRIPT
#
#
#-------------------------------------------------------------------------------
print ('***** Starting.....')
if __name__ == '__main__':
main()