forked from sonic-net/sonic-utilities
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnbrshow
More file actions
273 lines (211 loc) · 7.91 KB
/
nbrshow
File metadata and controls
273 lines (211 loc) · 7.91 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
#!/usr/bin/env python3
"""
Script to show Ipv4/Ipv6 neighbor entries
usage: nbrshow [-h] [-ip IPADDR] [-if IFACE] v
optional arguments:
-ip IPADDR, --ipaddr IPADDR
Neigbhor for a specific address
-if IFACE, --iface IFACE
Neigbhors learned on specific L3 interface
Example of the output:
admin@str~$nbrshow -4
Address MacAddress Iface Vlan
------------ ----------------- --------------- ------
10.0.0.57 52:54:00:87:8f:2c PortChannel0001 -
10.64.246.1 00:00:5e:00:01:f6 eth0 -
192.168.0.2 24:8a:07:4c:f5:0a Ethernet20 1000
..
Total number of entries 10
admin@str:~$ nbrshow -6 -ip fc00::72
Address MacAddress Iface Vlan Status
--------- ----------------- --------------- ------ ---------
fc00::72 52:54:00:87:8f:2c PortChannel0001 - REACHABLE
Total number of entries 1
"""
import argparse
import json
import sys
import subprocess
import re
from natsort import natsorted
from utilities_common import port_util
from swsscommon.swsscommon import SonicV2Connector
from tabulate import tabulate
"""
Base class for v4 and v6 neighbor.
"""
class NbrBase(object):
HEADER = []
NBR_COUNT = 0
def __init__(self, cmd):
super(NbrBase, self).__init__()
self.db = SonicV2Connector(host="127.0.0.1")
self.if_name_map, self.if_oid_map = port_util.get_interface_oid_map(self.db)
self.if_br_oid_map = port_util.get_bridge_port_map(self.db)
self.fetch_fdb_data()
self.cmd = cmd
self.err = None
self.nbrdata = []
return
def fetch_fdb_data(self):
"""
Fetch FDB entries from ASIC DB.
@Todo, this code can be reused
"""
self.db.connect(self.db.ASIC_DB)
self.bridge_mac_list = []
fdb_str = self.db.keys('ASIC_DB', "ASIC_STATE:SAI_OBJECT_TYPE_FDB_ENTRY:*")
if not fdb_str:
return
if self.if_br_oid_map is None:
return
oid_pfx = len("oid:0x")
for s in fdb_str:
fdb_entry = s
fdb = json.loads(fdb_entry .split(":", 2)[-1])
if not fdb:
continue
ent = self.db.get_all('ASIC_DB', s, blocking=True)
br_port_id = ent["SAI_FDB_ENTRY_ATTR_BRIDGE_PORT_ID"][oid_pfx:]
if br_port_id not in self.if_br_oid_map:
continue
port_id = self.if_br_oid_map[br_port_id]
if port_id in self.if_oid_map:
if_name = self.if_oid_map[port_id]
else:
if_name = port_id
if 'vlan' in fdb:
vlan_id = fdb["vlan"]
elif 'bvid' in fdb:
try:
vlan_id = port_util.get_vlan_id_from_bvid(self.db, fdb["bvid"])
if vlan_id is None:
# the case could be happened if the FDB entry has created with linking to
# default VLAN 1, which is not present in the system
continue
except Exception:
vlan_id = fdb["bvid"]
print("Failed to get Vlan id for bvid {}\n".format(fdb["bvid"]))
self.bridge_mac_list.append((int(vlan_id),) + (fdb["mac"],) + (if_name,))
return
def fetch_nbr_data(self):
"""
Fetch Neighbor data (ARP/IPv6 Neigh) from kernel.
"""
p = subprocess.Popen(self.cmd, shell=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output, err) = p.communicate()
rc = p.wait()
if rc == 0:
rawdata = output
else:
self.err = err
rawdata = None
return rawdata
def display(self, vpos=3):
"""
Display formatted Neighbor entries (ARP/IPv6 Neigh).
"""
output = []
for ent in self.nbrdata:
self.NBR_COUNT += 1
vlan = '-'
if 'Vlan' in ent[2]:
vlanid = int(re.search(r'\d+', ent[2]).group())
mac = ent[1].upper()
fdb_ent = next((fdb for fdb in self.bridge_mac_list[:]
if fdb[0] == vlanid and fdb[1] == mac), None)
vlan = vlanid
if fdb_ent is not None:
ent[2] = fdb_ent[2]
else:
ent[2] = '-'
ent.insert(vpos, vlan)
output.append(ent)
self.nbrdata = natsorted(output, key=lambda x: x[0])
print(tabulate(self.nbrdata, self.HEADER))
print("Total number of entries {0} ".format(self.NBR_COUNT))
def display_err(self):
print("Error fetching Neighbors: {} ".format(self.err))
class ArpShow(NbrBase):
HEADER = ['Address', 'MacAddress', 'Iface', 'Vlan']
CMD = "/usr/sbin/arp -n "
def __init__(self, ipaddr, iface):
if ipaddr is not None:
self.CMD += ipaddr
if iface is not None:
self.CMD += ' -i ' + iface
NbrBase.__init__(self, self.CMD)
return
def display(self):
"""
Format "arp -n" output from kernel
Address HWtype HWaddress Flags Mask Iface
10.64.246.2 ether f4:b5:2f:79:b3:f0 C eth0
10.0.0.63 ether 52:54:00:ae:11:49 C PortChannel0004
"""
self.arpraw = self.fetch_nbr_data()
if self.arpraw is None:
self.display_err()
return
for line in self.arpraw.splitlines()[1:]:
if 'ether' not in line.split():
continue
ent = line.split()[::2]
self.nbrdata.append(ent)
super(ArpShow, self).display()
class NeighShow(NbrBase):
HEADER = ['Address', 'MacAddress', 'Iface', 'Vlan', 'Status']
CMD = "/bin/ip -6 neigh show "
def __init__(self, ipaddr, iface):
if ipaddr is not None:
self.CMD += ipaddr
if iface is not None:
self.CMD += ' dev ' + iface
self.iface = iface
NbrBase.__init__(self, self.CMD)
return
def display(self):
"""
Format "ip -6 neigh show " output from kernel
"fc00::76 dev PortChannel0002 lladdr 52:54:00:33:90:d0 router REACHABLE"
Format "ip -6 neigh show dev PortChannel0003"
"fc00::7a lladdr 52:54:00:6b:1d:0a router STALE"
"""
self.arpraw = self.fetch_nbr_data()
if self.arpraw is None:
self.display_err()
return
for line in self.arpraw.splitlines()[:]:
split = line.split()
if 'lladdr' not in split:
continue
ent = split[::2]
if 'router' not in split:
ent.append(split[-1])
if self.iface is not None:
ent.insert(2, self.iface)
else:
ent[1], ent[2] = ent[2], ent[1]
self.nbrdata.append(ent)
super(NeighShow, self).display()
def main():
parser = argparse.ArgumentParser(description='Show Neigbhor entries',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('-ip', '--ipaddr', type=str,
help='Neigbhor for a specific address', default=None)
parser.add_argument('-if', '--iface', type=str,
help='Neigbhors learned on specific L3 interface', default=None)
parser.add_argument('v', help='IP Version -4 or -6')
args = parser.parse_args()
try:
if (args.v == '-6'):
neigh = NeighShow(args.ipaddr, args.iface)
neigh.display()
else:
arp = ArpShow(args.ipaddr, args.iface)
arp.display()
except Exception as e:
print(str(e))
sys.exit(1)
if __name__ == "__main__":
main()