首先是下载snmpwalk,这个在csdn中有其他文档支持,不做过多描述
前置所需的csv文件配置如下,各位也可按照自己所需来配置列名
在test.csv文件中的信息如下
其中ip为设备的IP地址,inbps是流入流量值,outbps是流出流量值,port为对应端口
可在Ubuntu系统中使用下列代码来获取端口的oid值
snmpwalk -v 2c -c 团体名 设备ip地址 1.3.6.1.2.1.2.2.1.2
输出结果如下
红框框圈出来的部分就是每个端口对应的oid值
执行代码如下
# coding=gbk
import pandas as pd
import os
import time
import warnings
import multiprocessing as mp
warnings.simplefilter(action='ignore', category=FutureWarning)
#从snmp获取信息
def snmpWalk(host, oid):
getinfo = os.popen('snmpwalk -v 2c -c SNMP团体名 ' + host + ' ' + oid).read().split(':')[-1]
return getinfo
#从snmp获取端口信息
def snmpport(host, portinfo):
getport = os.popen('snmpwalk -v 2c -c SNMP团体名 ' + host + ' ' + '1.3.6.1.2.1.2.2.1.2').read().split('\n')
for i in getport:
if portinfo in i:
get_port = (i.split()[0]).split('.')[-1]
return get_port
#获取流量大小
def getresult(host, oid):
print(host + '-------->')
try:
getinfo1 = int(snmpWalk(host,oid))
time.sleep(2)
getinfo2 = int(snmpWalk(host,oid))
i = 1
while getinfo1 == getinfo2:
i +=1
time.sleep(2)
getinfo2 = int(snmpWalk(host,oid))
if getinfo2 != getinfo1:
break
if getinfo2 > getinfo1:
getinfo = (getinfo2 - getinfo1)*8/(2*i*1024*1024)
elif getinfo2 < getinfo1:
#数据上限为18446744073709551615,过了就刷新
getinfo = (18446744073709551615 - getinfo1 + getinfo2)*8/(2*i*1024*1024)
getinfo = str('%.2f'%getinfo)
except (ValueError, TypeError) as e:
getinfo1 = 0
getinfo2 = 0
getinfo = "NA"
print("Error in inresult:", e)
print(getinfo1,getinfo2,"Get:",getinfo)
return getinfo
if __name__ == '__main__':
starttime = time.time()
current_directory = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(current_directory, 'result.csv')
print(file_path)
data = pd.read_csv(file_path,encoding='gbk')
for index, row in data.iterrows():
#对应的IP地址
inthost = row['intip']
ccnhost = row['ccnip']
#获取对应的物理端口地址
getccnport = row['ccnport']
getport = row['port']
ccnp = snmpport(ccnhost, getccnport)
time.sleep(0.05)
inp = snmpport(inthost, getport)
time.sleep(0.05)
#外网端口oid
inoid = '1.3.6.1.2.1.31.1.1.1.6.' + str(inp)
outoid = '1.3.6.1.2.1.31.1.1.1.10.' + str(inp)
#CCN端口oid
ccnin = '1.3.6.1.2.1.31.1.1.1.6.' + str(ccnp)
ccnout = '1.3.6.1.2.1.31.1.1.1.10.' + str(ccnp)
resultin = getresult(inthost , inoid)
resultout = getresult(inthost , outoid)
data.at[index, 'inbps'] = resultin
data.at[index, 'outbps'] = resultout
resultccnin = getresult(ccnhost , ccnin)
resultccnout = getresult(ccnhost , ccnout)
data.at[index, 'ccnin'] = resultccnin
data.at[index, 'ccnout'] = resultccnout
data.to_csv(file_path, index=False)
endtime = time.time()
changetime = endtime - starttime
print(changetime)