hello world

zabbix监控网络设备用户登陆

近年来网络安全一直很重要,我们管理着上百的网络设备,路由器交换机,什么时候被入侵了,黑客登陆设备了,在哪里登陆的设备,也许我们一无所闻,目前我好像还没有见过哪个网络监控工具有这个功能,因此今天我突发奇想一定要完成这个工作。

实现的思路和过程:

1、写一个Python脚本,通过调用snmp_cmds去读取目标设备的网络连接情况,脚本需要传入2个参数,目标IP和目标设备的读团体字

2、如果没有连接则返回1,如果有连接则返回2

3、如果本次获取和上一次获取的哈希值不一样,且上一次并非空,则返回2,触发告警,且将本次的哈希值写入到文件

4、通过zabbix的key不断的去获取连接情况。

但注意,我这里获取的内容是通过mailx来发送邮件的,你们可能需要自己对应修改或者配置自己的mailx

以下为代码:

#!/usr/bin/python
#

import os,sys,snmp_cmds,hashlib
TargetIP=sys.argv[1]
SNMP=sys.argv[2]
info=''
mFile='/dev/shm/'+TargetIP

tcpConnectCount=int(snmp_cmds.snmpget(TargetIP,'TCP-MIB::tcpCurrEstab.0',SNMP).strip())
if not os.path.exists(mFile):
    f=open(mFile,'w')
    f.write('f9e2eaaa42d9fe9e558a9b8ef1bf366f190aacaa83bad2641ee106e9041096e4')
    f.close()
if tcpConnectCount > 0:
    devName=snmp_cmds.snmpget(TargetIP,"sysName.0",SNMP).strip()
    info=info+'设备:'+TargetIP+'\t'+devName+'\n'
    info=info+'LocalAddress'.ljust(18)+'LocalPort'.ljust(12)+'RemoteAddress'.ljust(17)+'RemotePort'.ljust(12)+'Status'.ljust(12)+'\n'
    tcpConnState=[ i[-1] for i in snmp_cmds.snmpwalk(TargetIP,'tcpConnState',SNMP)]
    tcpConnLocalAddress=[ i[-1] for i in snmp_cmds.snmpwalk(TargetIP,'tcpConnLocalAddress',SNMP)]
    tcpConnLocalPort=[ i[-1] for i in snmp_cmds.snmpwalk(TargetIP,'tcpConnLocalPort',SNMP)]
    tcpConnRemAddress=[ i[-1] for i in snmp_cmds.snmpwalk(TargetIP,'tcpConnRemAddress',SNMP)]
    tcpConnRemPort=[ i[-1] for i in snmp_cmds.snmpwalk(TargetIP,'tcpConnRemPort',SNMP)]
    for i in range(len(tcpConnState)):
        info=info+tcpConnLocalAddress[i].ljust(18)+tcpConnLocalPort[i].ljust(12)+tcpConnRemAddress[i].ljust(17)+tcpConnRemPort[i].ljust(12)+tcpConnState[i].ljust(12)
    f=open(mFile,'r')
    pinfo=f.read()
    f.close()
    if hashlib.sha3_256(info.encode('utf-8')).hexdigest() != pinfo:
        sendmail='echo "' +info+'" | /usr/bin/mail -s "'+devName+' Loging warning" 623746291@qq.com'
        os.system(sendmail)
        f=open(mFile,'w')
        f.write(hashlib.sha3_256(info.encode('utf-8')).hexdigest())
        f.close()
        print(2)
    else:
        print(1)
else:
    print(1)

触发告警,触发第一次返回2,就告警,再执行,本次该机的tcp连接状态已保存,没有新增也没有减少,和上一次一样,没有变化,因此不会再告警

邮件已到

 

邮件内容显示连接建立的情况,可一目了然

 

 

posted @ 2020-03-29 23:56  浩天四哥  阅读(694)  评论(0)    收藏  举报