Python SNMP Trap Receiver

강동인 picture 강동인 · Jan 16, 2018 · Viewed 11.8k times · Source

I received an SNMP trap message in Python3, and I got a hexadecimal number.

How do I convert it to a String so I can see it?

Received Data(Hex)

b'0E\x02\x01\x01\x04\x06404040\xa78\x02\x04\x00\xf6\x17~\x02\x01\x00\x02\x01\x000*0\x0f\x06\x08+\x06\x01\x02\x01\x01\x03\x00C\x03\x01k+0\x17\x06\n+\x06\x01\x06\x03\x01\x01\x04\x01\x00\x06\t+\x06\x01\x06\x03\x01\x01\x05\x01'

This is my SNMP trap receiver code

import socket
import sys

port = 162
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
while 1:
        data, addr = s.recvfrom(4048)
        print(data)

This is my SNMP trap Sender code

from pysnmp.hlapi.asyncore import *

snmpEngine = SnmpEngine()
sendNotification(
    snmpEngine,
    CommunityData('404040'),
    UdpTransportTarget(('192.168.0.160', 162)),
    ContextData(),
    'trap',
    NotificationType(ObjectIdentity('SNMPv2-MIB', 'coldStart')),
 )

snmpEngine.transportDispatcher.runDispatcher()

Answer

Lightness Races in Orbit picture Lightness Races in Orbit · Dec 10, 2018

Your sending code correctly uses a library to do all the encoding/decoding for you.

Your receiving code does not. Even if you were to reinterpret the binary data as a string, you wouldn't be able to make much sense of it. It is an SNMP PDU with lots of delicious information in it that you'd have to extract and parse.

The proper thing to do is get an SNMP library to decode it for you and provide a nice logical value representing what you've received. PySNMP has this facility already. Here's an example.