第一部分,观察通过snmp OID能获取的信息,对信息进行关联。
1、通过 snmp获取到接口IP地址和掩码信息,发现IP地址作为索引值;
2、每个IP地址的索引,都可以关联到接口的索引
3、每个接口索引,都可以通过snmp获取到接口的名称,
降这个3个数据进行关联,可以得到接口名称和网段信息的关联。
第二部分:通过代码实现。
get_vlan_network.py
import re,os,ipaddress
#get the interface Vlan value
def get_Vlanif_value(host,SNMP_community):
vlan_dict = {}
pattern = re.compile(r'(\d+)\s*=\s*STRING:\s*(\S+)')
cmd = "snmpwalk -v 2c -c " + SNMP_community +" "+ host + " ifname | grep Vlan" # 进行过滤,仅显示VLAN接口
tmp = os.popen(cmd).readlines()
# print("begin:",tmp)
for i in tmp:
matches = re.search(pattern, i)
if matches:
if_id = matches.group(1) #if_id: interface_snmp_ID
Vlan_value = re.search(r'\d+', matches.group(2)).group()
# print(if_id,Vlan_value)
vlan_dict[if_id] = Vlan_value
return vlan_dict
# VLAN = get_Vlan_value(host)
# print(VLAN)
# get the interface ip address and inetface snmp ID
def get_if_ip(host,SNMP_community):
if_dict = {}
pattern = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) = INTEGER: (\d+)'
cmd = "snmpwalk -v 2c -c " + SNMP_community +" "+ host + " .1.3.6.1.2.1.4.20.1.2"
tmp = os.popen(cmd).readlines()
for i in tmp:
matches = re.search(pattern, i)
if matches:
ip_address = matches.group(1)
if_id = matches.group(2)
if_dict[ip_address] = if_id
return if_dict
# IF_value = get_if_ip(host)
# print(IF_value)
def get_network_value(host,SNMP_community):
network_dict = {}
pattern = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) = IpAddress: (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
cmd = "snmpwalk -v 2c -c " + SNMP_community +" " + host + " .1.3.6.1.2.1.4.20.1.3 | grep -wv -e 255.255.255.255"
tmp = os.popen(cmd).readlines()
for i in tmp:
matches = re.search(pattern, i)
if matches:
ip_address = matches.group(1)
subnet_mask = matches.group(2)
network_str = f"{ip_address}/{subnet_mask}"
network = ipaddress.IPv4Network(network_str, strict=False)
network_dict[ip_address] = network.with_prefixlen
return network_dict
def get_network_subnet_Vlan(host,SNMP_community):
# 将网段信息与VLAN ID进行关联
Netowrk_Vlan ={}
Vlan_info = get_Vlanif_value(host, SNMP_community)
If_info = get_if_ip(host, SNMP_community)
Network_info = get_network_value(host, SNMP_community)
# print(host,SNMP_community)
for k ,v_net in Network_info.items():
# print(k)
if k in If_info:
# Netowrk_Vlan[v_net]
if If_info[k] in Vlan_info: #Vlan_info 进行了过滤,
# print( v_net, Vlan_info[If_info[k]])
Netowrk_Vlan[v_net]=Vlan_info[If_info[k]]
return Netowrk_Vlan
if __name__ == '__main__':
with open('host_snmp.txt', 'r', encoding='utf8') as f:
for line in f:
dict = {}
host = line.split(" ")[0]
snmp_community = (line.split(" ")[1]).strip()
# print(host,snmp_community)
#将所有数据放入字典
dict[host] = get_network_subnet_Vlan(host,snmp_community)
print(dict)
将设备IP地址、snmp团体字保存再host_snmp.txt 文件中,每行一台设备,通过脚本遍历进行查询。
将结果保存为字典格式,便于后续对数据进行利用。
文件存储格式:
host_ip snmp_commuinty
数据数据格式:
{'host_ip':{network/mask':'vlan_id',network/mask':'vlan_id'}}