/
sdwan.py
280 lines (217 loc) · 8.04 KB
/
sdwan.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
import argparse
import getpass
import json
import re
import sys
from pprint import pprint
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
from rest_api_lib import RestSdwan
class GetDataVmanage(RestSdwan):
def __init__(self,
info_overview=["vdevice-host-name",
"vdevice-name",
"ifname",
"ip-address",
"if-oper-status",
"vpn-id",
"mtu",
"uptime",
"port-type",
"description"],
*args,
**kwargs):
super().__init__(*args, **kwargs)
pd.set_option('display.max_rows', None)
self.dataframe = pd.DataFrame()
self.info_overview = info_overview
def all_device_id(self):
"""
get all device id from vmanage
:return:
list of deviceId
:return type:
list
"""
response = self.get_request('/device', 'json')
id_devices = list()
for data in response['data']:
id_devices.append(data['deviceId'])
return id_devices
def device_overview(self, deviceId):
"""
get data from deviceid
"""
info_overview = self.info_overview
url = f'/device/interface?deviceId={deviceId}'
response = self.get_request(url, 'json')
# prepare container
list_data = list()
# if deviceId doesn't have attribute 'data'
if not "data" in response:
data_overview = dict()
for info in info_overview:
data_overview[info] = deviceId if info == "vdevice-name" else None
list_data.append(data_overview)
return list_data
for data in response['data']:
data_overview = dict()
for info in info_overview:
data_overview[info] = data[info] if info in data else None
list_data.append(data_overview)
return list_data
def all_device_overview(self, devices=[]):
for device in devices:
data = self.device_overview(device)
self.dataframe = self.dataframe.append(data)
return self.dataframe
class GetTopology(RestSdwan):
"""
Get topology from BSD session
"""
def __init__(self, *args, **kwargs):
"""
call init function from class RestSdwan
include invoke login()
"""
super().__init__(*args, **kwargs)
def all_device_id(self):
"""
get all device id from vmanage
:return:
list of deviceId
:return type:
list
"""
response = self.get_request('/device', 'json')
id_devices = list()
for data in response['data']:
id_devices.append(data['deviceId'])
return id_devices
def datakey_bsd_session_deviceId(self, deviceId):
"""
get bsd session, attribute: vdevice-datakey
return list of tuple
"""
url = f'/device/bfd/sessions?deviceId={deviceId}'
response = self.get_request(url, 'json')
regex = r'vdevice-dataKey": "([0-9.]+-[\w]+)-([0-9.]+-[\w]+)-[\w]+"'
tuples = re.findall(regex, json.dumps(response))
return tuples
def datakey_bsd_session_all(self):
"""
get bsd session in all deviceId
"""
deviceId = self.all_device_id()
print('deviceId: ', end='')
pprint(deviceId)
tuple_data = list()
for device in deviceId:
tunnel = self.datakey_bsd_session_deviceId(device)
tuple_data.append(tunnel)
tunnels = list()
df = pd.DataFrame()
for data in tuple_data:
for d in data:
if not d in tunnels:
swap_d = (d[1], d[0])
if not swap_d in tunnels:
tunnels.append(d)
df = df.append({'from': d[0], 'to': d[1]}, ignore_index=True)
return df
class MyParser(argparse.ArgumentParser):
"""
overwrite error message
"""
def error(self, err):
sys.stderr.write(f'error: {err}\n')
self.print_help()
sys.exit(1)
def parser():
# create the parser
my_parser = MyParser(description='Use REST API SDWAN to retrieve data')
subparser = my_parser.add_subparsers(dest='command')
subparser.required = True
status_interface = subparser.add_parser('status',
description='Get interace status table')
# add the arguments in subparser status_interface
status_interface.add_argument('Vmanage',
metavar='vmanage:port',
type=str,
help='vmanage ip address and port')
status_interface.add_argument('Username',
metavar='username',
type=str,
help='username login to vmanage')
status_interface.add_argument('-a',
action='store_true',
help='show all deviceId')
status_interface.add_argument('-d',
action='store',
type=str,
help='deviceId IP address')
status_interface.add_argument('-q',
action='append',
type=str,
help='attribute data to be retrieve')
topology = subparser.add_parser('topology',
description='Get topology graph')
# add the arguments in subparser status_interface
topology.add_argument('Vmanage',
metavar='vmanage:port',
type=str,
help='vmanage ip address and port')
topology.add_argument('Username',
metavar='username',
type=str,
help='username login to vmanage')
return my_parser.parse_args()
def main():
print('_' * 50 + '\n')
args = parser()
username = args.Username
vmanage = args.Vmanage
password = getpass.getpass(f'Password {username}: ')
# run topology parser
if args.command == 'topology':
print('preparing topology data...')
obj = GetTopology(vmanage_ip=vmanage, username=username, password=password)
topo = obj.datakey_bsd_session_all()
print('Network topology: ')
pprint(topo)
G = nx.from_pandas_edgelist(topo, 'from', 'to')
nx.draw(G, with_labels=True)
plt.show()
sys.exit(0)
elif args.command == 'status':
# custom or default attribute will be displayed
if not args.q:
data_attribute = None
obj = GetDataVmanage(vmanage_ip=vmanage, username=username, password=password)
else:
data_attribute = args.q
obj = GetDataVmanage(vmanage_ip=vmanage, username=username, password=password,
info_overview=data_attribute)
if args.a:
allDeviceId = obj.all_device_id()
print("all deviceId : ")
for device in allDeviceId:
print(device, end="\n")
sys.exit()
if not args.d:
# all deviceId
allDeviceId = obj.all_device_id()
print(f"Retrieving data {len(allDeviceId)} deviceId in {vmanage}")
all_device_overview = obj.all_device_overview(allDeviceId)
print(all_device_overview)
else:
# certain deviceId
print(f"Retrieving data from deviceId {args.d} in {vmanage}")
df_deviceId = pd.DataFrame()
data_deviceId = obj.device_overview(args.d)
df_deviceId = df_deviceId.append(data_deviceId)
print(df_deviceId)
print('_' * 50 +'\n')
if __name__ == "__main__":
main()