本文深入探討了Go語言中的代碼包和包引入機制,從基礎概念到高級應用一一剖析。文章詳細講解瞭如何創建、組織和管理代碼包,以及包引入的多種使用場景和最佳實踐。通過閱讀本文,開發者將獲得全面而深入的理解,進一步提升Go開發的效率和質量。 關註公眾號【TechLeadCloud】,分享互聯網架構、雲服務技術 ...
第一部分,觀察通過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'}}