Centos7 configuration install snmp

1. Install snmp

1. Centos7+yum installation

 yum -y install net-snmp net-snmp-utils

2. Change the configuration file snmpd.conf

 vi /etc/snmp/snmpd.conf

Add the community as public, named notConfigUser
Insert picture description here
Insert picture description here

Restart (restart every time you modify the configuration file)

systemctl restart snmpd

3. Test

1. Check the open ports of tcp and udp

netstat -tulnp
# 查询主机信息
snmpwalk -v 2c -c public 10.0.12.59 system

The following content indicates success
Insert picture description here

2. Set v3

1. Stop the service

systemctl stop snmpd

2. Setting

net-snmp-create-v3-user

Insert picture description here
It is recommended to set a longer password, otherwise the setting will fail

tail -n 5 /var/lib/net-snmp/snmpd.conf

Insert picture description here
3. Verification

snmpwalk -v3 -usuperuser -lauth -A "snmpv3@2020md5" -X "snmpv3@2020des" 10.0.12.59

Insert picture description here
If the following error is reported, it proves that the setting has failed. The reason may be that the password setting is too short. You
Insert picture description here
need to reset the password

3. Python implements snmp service

# @DESC   :实现snmp协议(简单网络管理协议),只有安装了snmp系统(管理信息库(MIB)、管理信息结构(SMI)及SNMP报文协议)的主机才会有响应
#  使用snmpwalk -v -2c -c public ip system 查看操作系统信息  (snmpbulkwalk代替snmpwalk)
#  -v:指定snmp的版本, 1或者2c或者3
# –c:指定连接设备SNMP密码。
# snmp能够获取系统信息,内存信息,cpu信息,磁盘信息,有对应的oid
import datetime
import os
import shlex
import signal
import subprocess

from pysnmp.hlapi import *

# 获取系统信息
def run_snmp(host, public='public', v=1, timeout=3,authuser="superuser",md5pwd="snmpv3@2020md5",secpwd="snmpv3@2020des"):
    """
    :param host:        ip
    :param public:      社区名
    :param v:           版本1:v2,0:v1
    :param timeout:     超时时间
    :param authuser:    v3 认证用户
    :param md5pwd:      md5 加密密码
    :param secpwd:      sec 假面描姆
    :return:
    """
    if v == 0 or v == 1:
        errorIndication, errorStatus, errorIndex, varBinds = next(getCmd(
            SnmpEngine(),
            CommunityData(public, mpModel=v),
            UdpTransportTarget((host, 161), timeout=timeout),
            ContextData(),
            ObjectType(ObjectIdentity('SNMPv2-MIB', 'sysDescr', 0)))
            )
        if varBinds:
            return ' = '.join([x.prettyPrint() for x in varBinds])
    else:
        # v3进行验证
        command = 'snmpwalk -v3 -u{authuser} -lauth -A "{md5pwd}" -X "{secpwd}" {host} sysDescr'.format(
            authuser=authuser, md5pwd=md5pwd, secpwd=secpwd, host=host)
        command_split = shlex.split(command)
        process = subprocess.Popen(command_split, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        start_time = datetime.datetime.now()
        try:
           while process.poll() is None:
                now_time = datetime.datetime.now()
                if (now_time-start_time).seconds > 3:
                    try:
                        os.kill(process.pid,signal.SIGTERM)
                    except OSError as e:
                        print(e,process.pid)
                stdout,stderr = process.communicate()
                return stdout.decode()
        except:
            return False


def analysis_snmp(snmp_str):
    """
    解析snmp响应
    :param snmp_str: SNMPv2-MIB::sysDescr.0 = Linux localhost.localdomain 3.10.0-1127.18.2.el7.x86_64 #1 SMP Sun Jul 26 15:27:06 UTC 2020 x86_64
    :return: {"version":"3.10.0-1127.18.2.el7.x86_64","os":"Linux"}
    """
    msg = {
    
    }
    print('snmp_str',snmp_str)
    if isinstance(snmp_str, str):
        pattern = r'\d+\.(?:\w+\.)*\w+'
        version_ = re.findall(pattern, snmp_str)
        version = "-".join(version_)
        print('版本信息为:', version)
        msg['version'] = version
        ospatter = r'SNMPv2-MIB::sysDescr.0 = (?:[a-zA-Z0-9]+[ |-]?[a-zA-Z0-9])*'
        os_ = re.findall(ospatter, snmp_str)
        os = "".join(os_).replace("SNMPv2-MIB::sysDescr.0 = ", "")
        msg['os'] = os
        print('系统/设备为:', os)
    return msg



if __name__ == '__main__':
    import re

    # host_list = ['10.0.12.59','10.0.12.57','10.0.10.1','10.0.10.255','10.0.10.254']
    for i in host_list:
        str_msg = run_snmp(i)
        analysis_snmp(str_msg)
    Snmp_trap()

4. Additional

Setting modification (only v1, v2, because v3 I will not)
add in the configuration file

rwcommunity private default
rwcommunity6 private default

Insert picture description here
verification:

snmpset -c private -v 1 ip SNMPv2-MIB::sysName.0 s ubuntu

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43076825/article/details/109532709