-
Notifications
You must be signed in to change notification settings - Fork 92
/
XMC_NBI.py
894 lines (801 loc) · 31.3 KB
/
XMC_NBI.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
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
#!/usr/bin/env python
###########################################################################
#
# written by Markus Nikulski
# created 01. Sep. 2020
# updated 07. Mar. 2022
# updated 02. Feb. 2023 issue #155 fix for "empty error message"
#
# tested against XMC 8.5.7 release
# tested against XIQ-SE 21.11.11.37 release
#
# Note: this is class is not offical supported by Extreme Networks
#
###########################################################################
import sys, json, time, base64, logging
from datetime import datetime
import requests
import urllib3
urllib3.disable_warnings() # supress SSL certificate warning
#import requests_debugger # pip install requests-debugger
#requests_debugger.set( max_depth = 5 )
logger = None
debug = False
getframe_expr = 'sys._getframe({}).f_code.co_name' # is required to determinant the call of a routine
#####################################################################################################
class XMC_NBI():
'''XMC NBI interface'''
__version__ = "0.0.4"
__author__ = "Markus Nikulski ([email protected])"
#################################################################################################
def __init__(self, host: str, clientId: str , secret: str , test: bool = False ):
global logger
if not logging.getLogger().hasHandlers():
logging.basicConfig( level = logging.WARNING )
logger = logging.getLogger()
if debug:
from http.client import HTTPConnection
HTTPConnection.debuglevel = 1
logger.setLevel( logging.DEBUG )
logger.debug("XMC NBI version %s" % XMC_NBI.__version__)
self.nbiUrl = 'https://' + host + ':8443/nbi/graphql' # API URL
self.host = host # XMC IP address or FQDN
self.port = 8443 # TCP port
self.clientId = clientId # API authentication
self.secret = secret # API authentication
self.timeout = 10 # session timeout in seconds
self.token = None
self.data = None # last query result
self.test = test # test mode (boolean)
self.error = False # error tracker (boolen)
self.message = '' # error message
self.expire = 0 # time when the session will expire
self.renewTime = 90 # in procentage of the max expire time
if self.test == False and debug:
self.test = True
self.session = self._login()
if not self.error:
self._pull_schema()
#################################################################################################
def __repr__(self):
return '%s' % self.__dict__
#################################################################################################
def __del__(self):
if self:
if self.session:
self.session.close()
#################################################################################################
def _computeExpireTime(self, TimeStart, TimeEnd):
'''internal use only'''
timeDiff = TimeEnd - TimeStart
unixtime = time.mktime( datetime.today().timetuple() )
return unixtime + ( timeDiff.total_seconds() / 100 * self.renewTime )
#################################################################################################
def _ifExpire(self):
'''internal use only'''
if self.expire > time.mktime( datetime.today().timetuple() ):
return False
else:
return True
#################################################################################################
def _login(self):
'''internal use only'''
token_url = 'https://'+ self.host +':'+ str(self.port) +'/oauth/token/access-token?grant_type=client_credentials'
headers = {"Content-Type" : "application/x-www-form-urlencoded"}
try:
response = requests.post(token_url, auth=(self.clientId, self.secret), headers=headers, verify=False, timeout=5)
except requests.Timeout as error:
self.message = "timeout reached, host '%s' not responding" % self.host
self.error = True
return False
except requests.TooManyRedirects as error:
self.message = "too many redirects"
self.error = True
return False
except requests.RequestException as error:
self.message = "No connection could be made because the target machine actively refused it"
self.error = True
return False
except requests.ConnectionError as error:
self.message = "connection error '%s'" % error
self.error = True
return False
if response.status_code == requests.codes.ok: # 200
result = response.json()
self.token = result[u'access_token']
xmcTokenElements = self.token.split('.')
tokenData = json.loads( base64.b64decode(xmcTokenElements[1]+ "==") )
self.expire = self._computeExpireTime( datetime.fromtimestamp( tokenData['iat'] ), datetime.fromtimestamp( tokenData['exp'] ) )
logger.debug(' Issuer: %s' % tokenData['iss'] )
logger.debug(' Subject: %s' % tokenData['sub'] )
logger.debug(' JWT ID: %s' % tokenData['jti'] )
logger.debug(' XMC-Roles: %s' % tokenData['roles'] )
logger.debug(' Issued at: %s' % datetime.fromtimestamp( tokenData['iat'] ) )
logger.debug(' Expiration Time: %s' % datetime.fromtimestamp( tokenData['exp'] ) )
logger.debug(' Not Before: %s' % datetime.fromtimestamp( tokenData['nbf'] ) )
session = requests.Session()
session.verify = False
session.timeout = self.timeout
session.headers.update({'Accept': 'application/json',
'Content-type': 'application/json',
'Authorization': 'Bearer ' + self.token,
'Cache-Control': 'no-cache',
})
return session
elif response.status_code == requests.codes.unauthorized: # 401
self.message = "authentication failed"
self.error = True
elif response.status_code == requests.codes.not_found: # 404
self.message = "HTTP-ERROR: URL not found"
self.error = True
else:
self.message = "HTTP-ERROR: " + response.status_code
self.error = True
return False
#################################################################################################
def _call(self, query: str):
'''internal use only'''
if self._ifExpire():
logger.debug("XMC NBI session expired, force re-login")
self.expire = 0
self.session = self._login()
logger.debug("query: %s" % query)
return self._decode_response( self.session.post( self.nbiUrl, json = {'query': query} ), eval(getframe_expr.format(2)) )
#################################################################################################
def _decode_response(self, response: str, caller: str):
'''internal use only'''
data_out = None
self.error = False
if response.status_code != requests.codes.ok:
self.message = 'HTTP-ERROR: ' + response.reason + ' (' + str(response.status_code) + ')'
self.error = True
else:
try:
data_out = json.loads(response.text)
except:
self.message = "call '%s' no JSON data given" % caller
self.error = True
if not self.error:
if data_out['data'] == None:
self.message = data_out['errors'][0]['message']
self.error = True
if self.error:
self.message = 'call execution error: "%s"' % self.message
self.error = True
self.data = None
return False
else:
if self.test or debug:
callTine = float("{0:0.1f}".format( response.elapsed.total_seconds() * 1000 ))
logger.debug('call %s executed [%s ms]' % (caller, callTine) )
self.data = data_out['data']
return True
#################################################################################################
def _pull_schema(self):
'''is just a API test call'''
schema_nurl = 'https://'+ self.host +':'+ str(self.port) +'/nbi/graphql/schema.idl'
response = self.session.get(schema_nurl)
if response.status_code == requests.codes.ok: # 200
self.schema = response.text
else:
self.message = "pull NBI schema failed"
self.error = True
#################################################################################################
def query(self, query: str):
''' provide NBI graphql code'''
if self._call( query ):
return self.data
else:
return False
#################################################################################################
def getSites(self):
'''pull all sites'''
query = '{ network { sites { mapPaths siteName } } }'
if self._call( query ):
return self.data['network']['sites'][0]['mapPaths']
else:
return False
#################################################################################################
def addSite(self, name: str):
'''create a site'''
query = '''
mutation {
network {
createSite(input: {siteLocation: "<NAME>"}) {
status
message
}
}
}
'''
if self._call( query.replace('<NAME>', name) ):
if self.data['network']['createSite']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['network']['createSite']['message']
self.error = True
return False
else:
return False
#################################################################################################
def deleteSite(self, name: str):
'''delete a site'''
query = '''
mutation {
network {
deleteSite(input: {siteLocation: "<NAME>"}) {
status
message
}
}
}
'''
if name == "/World":
self.message = 'Site /World is not allowed to be deleted'
self.error = True
return False
if self._call( query.replace('<NAME>', name) ):
if self.data['network']['deleteSite']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['network']['deleteSite']['message']
self.error = True
return False
else:
return False
#################################################################################################
def getDevices(self):
'''pull all devices'''
query = '{ network { devices { ip nickName } } }'
if self._call( query ):
return self.data['network']['devices']
else:
return False
#################################################################################################
def getDevice(self, ip: str):
'''pull device details based on IP address'''
query = '''
{ network { device(ip: "<IP>") {
firmware
sitePath
status
sysName
sysContact
sysLocation
deviceData {
serialNumber
family
subFamily
}
nosIdName
} } }
'''
if self._call( query.replace('<IP>', ip) ):
returnData = {}
if not self.data['network']['device'] == None:
for key, value in self.data['network']['device'].items():
if key == 'deviceData':
for key2, value2 in value.items():
returnData[key2] = value2
elif key == 'status':
if value == 1:
returnData[key] = 'up'
else:
returnData[key] = 'down'
else:
returnData[key] = value
return returnData
else:
return None
else:
return False
#################################################################################################
def getMacAddresses(self):
'''pull all AMC addresses'''
query = '''
{
accessControl {
allGroups {
description
typeStr
name
values
}
}
}
'''
if self._call( query ):
returnData = {}
for group in self.data['accessControl']['allGroups']:
if group['typeStr'] == 'MAC':
for mac in group['values']:
returnData[mac] = group['name']
return returnData
else:
return None
#################################################################################################
def getMacAddress(self, mac: str):
'''pull MAC details based on MAC address'''
query = '''
{ accessControl {
endSystemInfoByMac(macAddress: "<MAC>") {
endSystemInfo {
custom1
custom2
custom3
custom4
memberOfGroups
groupDescr1
}
} } }
'''
if self._call( query.replace('<MAC>', mac) ):
if not self.data['accessControl']['endSystemInfoByMac']['endSystemInfo'] == None:
returnData = {}
for key, value in self.data['accessControl']['endSystemInfoByMac']['endSystemInfo'].items():
if key == 'groupDescr1':
returnData['groupDescription'] = value
elif key == 'memberOfGroups':
returnData['groups'] = value
else:
returnData[key] = value
return returnData
else:
return None
else:
return False
#################################################################################################
def addMacAddress(self, mac, group, description: str = '', custom1: str = ''):
'''add MAC using MAC address, group'''
query = '''
mutation {
accessControl {
addMACToEndSystemGroup(input: {
group: "<GROUP>"
value: "<MAC>"
description: "<DESCRIPTION>"
custom1: "<CUSTOM_1>"
reauthenticate: true
}) {
status
message
}
}
}
'''
query = query.replace('<MAC>', mac)
query = query.replace('<GROUP>', group)
query = query.replace('<DESCRIPTION>', description)
query = query.replace('<CUSTOM_1>', custom1)
if self._call( query ):
if self.data['accessControl']['addMACToEndSystemGroup']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['accessControl']['addMACToEndSystemGroup']['message']
self.error = True
return False
else:
return False
#################################################################################################
def delMacAddress(self, mac: str, group: str):
'''delete MAC based on MAC address'''
query = '''
mutation {
accessControl {
removeMACFromEndSystemGroup(input: {
group: "<GROUP>",
value: "<MAC>",
reauthenticate: true
}) {
status
message
}
}
}
'''
query = query.replace('<MAC>', mac)
query = query.replace('<GROUP>', group)
if self._call( query ):
if self.data['accessControl']['removeMACFromEndSystemGroup']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['accessControl']['removeMACFromEndSystemGroup']['message']
self.error = True
return False
else:
return False
#################################################################################################
def reauthenticateMacAddresses(self, mac: str):
'''force re-authentication if MAC address in End-System-Event'''
query = '''
mutation {
accessControl {
reauthenticate(input: { macAddress: "<MAC>" } )
{
status
message
} } }
'''
if self._call( query.replace('<MAC>', mac) ):
if self.data['accessControl']['reauthenticate']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['accessControl']['reauthenticate']['message']
self.error = True
return False
else:
return False
#################################################################################################
def getESGroups(self):
'''pull all NAC groups'''
query = '{ accessControl { endSystemCategoryGroupNames } }'
if self._call( query ):
return self.data['accessControl']['endSystemCategoryGroupNames']
else:
return False
#################################################################################################
def getESGroup(self, groupName: str):
'''get details about a NAC group'''
query = '''
{ accessControl {
group(name: "<GROUP>") {
description
name
typeStr
values
valueDescriptions
} } }
'''
if self._call( query.replace('<GROUP>', groupName) ):
if not self.data['accessControl']['group'] == None:
return self.data['accessControl']['group']
else:
return None
else:
return False
#################################################################################################
def createGroup(self, groupName: str, groupType: str, description: str = ''):
'''create NAC group'''
query = '''
mutation {
accessControl {
createGroup(input: {name: "<GROUP>", type: <TYPE>, description: "<DESC>"}) {
status
message
}
}
}
'''
query = query.replace('<GROUP>', groupName)
query = query.replace('<TYPE>', groupType)
query = query.replace('<DESC>', description)
if self._call( query ):
if self.data['accessControl']['createGroup']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['accessControl']['createGroup']['message']
self.error = True
return False
else:
return False
#################################################################################################
def deleteGroup(self, groupName: str):
'''delete NAC group'''
query = '''
mutation {
accessControl {
deleteGroup(input: {name: "<GROUP>"}) {
status
message
}
}
}
'''
if self._call( query.replace('<GROUP>', groupName) ):
if self.data['accessControl']['deleteGroup']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['accessControl']['deleteGroup']['message']
self.error = True
return False
else:
return False
#################################################################################################
def createGroupRuleProfilePolicy(self, group_name: str, vlanId: int, vlanName: str, cfgDomain: str = 'Default'):
'''create NAC group, rule, profile, policy'''
query = '''
mutation {
accessControl {
createDCMVirtualAndPhysicalNetwork(input: {
vlanName: "<VLAN-NAME>"
primaryVlanId: <VLAN-ID>
name: "<GROUP>"
nacConfig: "<CONFIG-DOMAIN>"
}) {
status
message
}
}
}
'''
query = query.replace('<GROUP>', group_name)
query = query.replace('<VLAN-ID>', str(vlanId))
query = query.replace('<VLAN-NAME>', vlanName)
query = query.replace('<CONFIG-DOMAIN>', cfgDomain)
if self._call( query ):
if self.data['accessControl']['createDCMVirtualAndPhysicalNetwork']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['accessControl']['createDCMVirtualAndPhysicalNetwork']['message']
self.error = True
return False
else:
return False
#################################################################################################
def createSwitch(self, ip: str, attrToSend: str, pGateway: str, sGateway: str = 'null'):
'''create switch in NAC'''
query = '''
mutation {
accessControl {
createSwitch(input: {
ipAddress: "<IP>"
primaryGateway: "<P-GATEWAY>"
secondaryGateway: <S-GATEWAY>
authType: ALL
attrsToSend: "<ATTR-TO-SEND>"
radiusAccountingEnabled: true
nacApplianceGroup: "Default"
}) {
status
message
}
}
}
'''
query = query.replace('<IP>', ip)
query = query.replace('<P-GATEWAY>', pGateway)
query = query.replace('<S-GATEWAY>', sGateway)
query = query.replace('<ATTR-TO-SEND>', attrToSend)
if self._call( query ):
if self.data['accessControl']['createSwitch']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['accessControl']['createSwitch']['message']
self.error = True
return False
else:
return False
#################################################################################################
def getSwitches(self):
'''pull all NAC switches'''
query = '''
{
accessControl {
allSwitches {
key
value {
GetAuthType
GetSwitchType
attributesToSend
authTypeStr
nacApplianceGroup
primaryGateway
radiusAccountingEnabled
secondaryGateway
sharedSecret
switchTypeStr
}
}
}
}
'''
if self._call( query ):
if not self.data['accessControl']['allSwitches'] == None:
newData = {}
for item in self.data['accessControl']['allSwitches']:
newData[ item['key'] ] = item['value']
return newData
else:
return None
else:
return False
#################################################################################################
def deleteSwitch(self, ip: str):
'''delete NAC switch'''
query = '''
mutation {
accessControl {
deleteSwitch(input: {
searchKey: "<IP>"
}) {
status
message
}
}
}
'''
if self._call( query.replace('<IP>', ip) ):
if self.data['accessControl']['deleteSwitch']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['accessControl']['deleteSwitch']['message']
self.error = True
return False
else:
return False
#################################################################################################
def enforceNacEnginesAll(self):
'''enforce all NAC engines'''
query = '''
mutation {
accessControl {
enforceAllAccessControlEnginesForceSwitchesAndPortal {
status
message
} } }
'''
if self._call( query ):
if self.data['accessControl']['enforceAllAccessControlEnginesForceSwitchesAndPortal']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['enforceAllAccessControlEnginesForceSwitchesAndPortal']['reauthenticate']['message']
self.error = True
return False
else:
return False
#################################################################################################
def enforceNacEngineDomain(self, name: str, ip: str = ''):
'''enforce specific NAC engines'''
query = '''
mutation {
accessControl {
enforceAccessControlEngines( input: {
engineGroup: "<NAME>"<ENGINE_IP>
}) {
status
message
}
}
}
'''
query = query.replace('<NAME>', name)
if ip == '':
query = query.replace('<ENGINE_IP>', '')
else:
query = query.replace('<ENGINE_IP>', ',engineIps: "'+ ip +'"')
if self._call( query ):
if self.data['accessControl']['enforceAccessControlEngines']['status'] == 'SUCCESS':
return True
else:
self.message = self.data['enforceAccessControlEngines']['reauthenticate']['message']
self.error = True
return False
else:
return False
#####################################################################################################
####################################### self test #########################################
#####################################################################################################
if __name__ == "__main__":
print(XMC_NBI.getDevices.__doc__)
print("##############################################################")
print(" DOCUMENTATION: " + XMC_NBI.__doc__ )
print(" CLASS: " + XMC_NBI.__name__ )
print(" VERSION: " + str(XMC_NBI.__version__) )
print(" AUTHOR: " + str(XMC_NBI.__author__) )
print("#############################################################")
print("## Self Test ##")
print("#############################################################")
debug = True
session = XMC_NBI('192.168.162.50', 'DVDnjOaqMQ', '8c12a0e1-87f8-4b18-a8d1-2e8c74d27c65', test=True)
if session.error:
print("ERROR: '%s'" % session.message)
sys.exit(1)
######
ip = "192.168.162.11"
data = session.query('{network{device(ip: "'+ ip +'"){nickName}}}')
if session.error:
print("ERROR: NBI query failed '%s'" % session.message )
sys.exit(1)
else:
if not data['network']['device'] == None:
print("INFO: query result device '%s' is '%s'" % (ip,data['network']['device']['nickName']) )
else:
print("INFO query result: device '%s' not given" % ip )
####
device_list = session.getDevices()
if session.error:
print("ERROR: get devices failed '%s'" % session.message )
sys.exit(1)
else:
print("INFO: query result of %s devices" % len( device_list ) )
for device in device_list:
data = session.getDevice( device['ip'] )
if session.error:
print("ERROR: get devices failed '%s'" % session.message)
sys.exit(1)
else:
if not data == None:
print("INFO: query result device '%s'" % device['ip'] )
for key, value in sorted( data.items() ):
print("%14s: %s" % (key, value) )
else:
print("WARN: device %s not found" % ip)
break
####
mac_list = session.getMacAddresses()
if session.error:
print("ERROR: get MACs failed '%s'" % session.message )
sys.exit(1)
else:
print("INFO: query result of %s MACs" % len( mac_list ) )
if not mac_list == None:
for mac, group in sorted( mac_list.items() ):
mac_data = session.getMacAddress( mac )
if session.error:
print("ERROR: get MAC '' failed '%s'" % (mac, session.message) )
sys.exit(1)
else:
if not mac_data == None:
print("%18s: %s" % ('MAC', mac) )
for key, value in sorted( mac_data.items() ):
print("%18s: %s" % (key, value) )
break
####
mac = '00:11:22:11:22:11'
group = 'Printers'
descr = 'is just a test'
if session.addMacAddress(mac, group, descr ):
print("INFO: add MAC address %s" % mac)
mac_data = session.getMacAddress( mac )
if session.error:
print("ERROR: get MAC '' failed '%s'" % (mac, session.message) )
sys.exit(1)
else:
if not mac_data == None:
for key, value in sorted( mac_data.items() ):
print("%18s: %s" % (key, value) )
if session.reauthenticateMacAddresses( mac ):
print("INFO: re-authenticate MAC address %s" % mac )
else:
print("WARNING: re-authenticate MAC address %s failed: '%s'" % (mac, session.message) )
if session.delMacAddress( mac, group ):
print("INFO: delete MAC address %s" % mac)
else:
print("INFO: delete MAC address %s failed: '%s'" % (mac, session.message) )
else:
print("INFO: add MAC address %s failed: '%s'" % (mac, session.message) )
####
group_list = session.getESGroups()
if session.error:
print("ERROR: get End System Groups failed '%s'" % session.message)
sys.exit(1)
else:
print("INFO: query result of %s End System Groups" % len( group_list ) )
for group_name in sorted( group_list ):
group_data = session.getESGroup( group_name )
if session.error:
print("ERROR: get End System Groups failed '%s'" % session.message)
sys.exit(1)
else:
print("INFO: query result of group '%s'" % group_name)
if not group_data == None:
for key, value in sorted( group_data.items() ):
print("%18s: %s" % (key, value) )
break
####
session.enforceNacEnginesAll()
if session.error:
print("ERROR: enfoced all NAC engines failed '%s'" % session.message)
sys.exit(1)
else:
print("INFO: enfoced all NAC engines")
####
nac_domain = 'Default'
session.enforceNacEngineDomain( nac_domain )
if session.error:
print("ERROR: enfoced %s NAC engine failed '%s'" % (nac_domain, session.message) )
sys.exit(1)
else:
print("INFO: enfoced %s NAC engine" % nac_domain)
sys.exit(0)