当前位置:   article > 正文

Python SNMP 获取交换机ARP表和FDB表(MAC和端口对应表)_mac vlan 端口 表 python snmp

mac vlan 端口 表 python snmp
  1. import sys
  2. import pysnmp.hlapi as hlapi
  3. import pysnmp.proto.rfc1902 as rfc1902
  4. def snmp_walk(host, oid, format='str', strip_prefix=True, community='public'):
  5. res = []
  6. for (errorIndication,
  7. errorStatus,
  8. errorIndex,
  9. varBinds) in hlapi.nextCmd(hlapi.SnmpEngine(),
  10. hlapi.CommunityData(community),
  11. hlapi.UdpTransportTarget((host, 161), timeout=4.0, retries=3),
  12. hlapi.ContextData(),
  13. hlapi.ObjectType(hlapi.ObjectIdentity(oid)),
  14. lookupMib=False,
  15. lexicographicMode=False):
  16. if errorIndication:
  17. raise ConnectionError(f'SNMP error: "{str(errorIndication)}". Status={str(errorStatus)}')
  18. elif errorStatus:
  19. raise ConnectionError('errorStatus: %s at %s' % (errorStatus.prettyPrint(),
  20. errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
  21. else:
  22. for x in varBinds:
  23. k, v = x
  24. if strip_prefix:
  25. k = str(k)[len(str(oid)) + 1:]
  26. if isinstance(v, rfc1902.Integer):
  27. res.append((str(k), int(v)))
  28. else:
  29. if format == 'numbers':
  30. res.append((str(k), v.asNumbers()))
  31. elif format == 'hex':
  32. res.append((str(k), v.asOctets().hex()))
  33. elif format == 'raw':
  34. res.append((str(k), v))
  35. elif format == 'bin':
  36. res.append((str(k), v.asOctets()))
  37. elif format == 'int':
  38. res.append((str(k), int(v)))
  39. elif format == 'preview':
  40. res.append((str(k), str(v)))
  41. elif format == 'any':
  42. try:
  43. res.append((str(k), v.asOctets().decode('utf-8')))
  44. except UnicodeDecodeError:
  45. res.append((str(k), '0x' + v.asOctets().hex()))
  46. elif format == 'str':
  47. res.append((str(k), v.asOctets().decode(v.encoding)))
  48. else:
  49. assert False, "Unknown format for walk()."
  50. res = {a: b for a, b in res}
  51. return res
  52. def split_numbers(oid):
  53. return [int(x) for x in oid.split('.')]
  54. def read_ipv4_from_oid_tail(oid, with_len=True):
  55. parts = [int(x) for x in oid.split('.')]
  56. if with_len:
  57. assert (parts[-5] == 4) # number of elements
  58. return '.'.join([str(x) for x in parts[-4:]])
  59. def read_bid_from_oid_tail(oid, with_len=True):
  60. parts = [int(x) for x in oid.split('.')]
  61. if with_len:
  62. assert (parts[-5] == 1) # number of elements
  63. return '.'.join([str(x) for x in parts[-1:]])
  64. def read_mac_from_oid_tail(oid, with_len=True):
  65. parts = [int(x) for x in oid.split('.')]
  66. if with_len:
  67. assert (parts[-5] == 6) # number of elements
  68. return '.'.join([str(x) for x in parts[-6:]])
  69. def machex(getvar):
  70. macs = getvar.split('.')
  71. i = 0
  72. ma = []
  73. for x in range(0, 6):
  74. maca = macs[i]
  75. if len(maca) == 1:
  76. a = hex(int(maca)).replace("x", "")
  77. else:
  78. a = hex(int(maca))[2:]
  79. ma.append(a)
  80. i = i + 1
  81. return ma[0] + ":" + ma[1] + ":" + ma[2] + ":" + ma[3] + ":" + ma[4] + ":" + ma[5]
  82. if __name__ == "__main__":
  83. # Read ARP table
  84. print(" - Reading device ARP table...", file=sys.stderr)
  85. atPhysAddress = snmp_walk('192.168.0.1', '1.3.6.1.2.1.3.1.1.2', 'hex', community='public')
  86. for oid, mac in atPhysAddress.items():
  87. ip = read_ipv4_from_oid_tail(oid, with_len=False)
  88. print(ip)
  89. print(mac)
  90. # Read dot1dBasePortIfIndex table
  91. print(" - Reading device dot1dBasePortIfIndex table...", file=sys.stderr)
  92. dot1dBasePortIfIndex = snmp_walk('192.168.0.1', '1.3.6.1.2.1.17.1.4.1.2', 'int', community='public')
  93. dot1dBasePort = {}
  94. for bid, id in dot1dBasePortIfIndex.items():
  95. ip = read_ipv4_from_oid_tail(bid, with_len=False)
  96. print('bid=', bid)
  97. print('id=', id)
  98. dot1dBasePort[bid] = str(id)
  99. print(dot1dBasePort)
  100. # Read ifDescr table
  101. print(" - Reading device ifDescr table...", file=sys.stderr)
  102. ifDescr = snmp_walk('192.168.0.1', '1.3.6.1.2.1.2.2.1.2', 'str', community='public')
  103. Descr = {}
  104. for id, desc in ifDescr.items():
  105. ip = read_ipv4_from_oid_tail(id, with_len=False)
  106. print('id=', id)
  107. print('desc=', desc)
  108. Descr[id] = desc
  109. print(Descr)
  110. dot1dBasePortDescr = {}
  111. for key in dot1dBasePort.keys():
  112. dot1dBasePortDescr[key] = Descr[dot1dBasePort[key]]
  113. print(dot1dBasePortDescr)
  114. # Read dot1qTpFdbPort table
  115. print(" - Reading device dot1qTpFdbPort table...", file=sys.stderr)
  116. dot1qTpFdbPort = snmp_walk('192.168.0.1', '1.3.6.1.2.1.17.4.3.1.2', 'int', community='public')
  117. dot1qTpFdb = {}
  118. for mac, bid in dot1qTpFdbPort.items():
  119. macdec = read_mac_from_oid_tail(mac, with_len=False)
  120. print('machex=', machex(macdec))
  121. print('bid=', bid)
  122. dot1qTpFdb[machex(macdec)] = str(bid)
  123. print(dot1qTpFdb)
  124. dot1qTpFdbDescr = {}
  125. for key in dot1qTpFdb.keys():
  126. if dot1qTpFdb[key] in dot1dBasePortDescr.keys():
  127. dot1qTpFdbDescr[key] = dot1dBasePortDescr[dot1qTpFdb[key]]
  128. print(dot1qTpFdbDescr)

测试思科、华为、H3C可以正常运行;

有些H3C设备没有提供

dot1qTpFdbPort(1.3.6.1.2.1.17.7.1.2.2.1.2)

需要使用

dot1dTpFdbPort

MAC地址对应的端口号。

1.3.6.1.2.1.17.4.3.1.2

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/156742
推荐阅读
相关标签
  

闽ICP备14008679号