Search code examples
pythonpysnmp

Sending SNMP messages from certain port by Pysnmp


I am getting signal information from a device in my network by using python pysnmp.

for (errorIndication, errorStatus, errorIndex, varBinds) in nextCmd(
        SnmpEngine(),
        UsmUserData(userName=config.transmitter_username, authKey=config.transmitter_authkey),
        UdpTransportTarget((X.X.X.X, 161), timeout=1.0, retries=0),
        ContextData(),
        ObjectType(ObjectIdentity(SNMP_INITIAL_INFO_OIDS[0][1])),
        lexicographicMode=False
):
    if errorIndication or errorStatus:

There is no problem with the request, but I am doing this periodically (once in every 5 seconds), and everytime I send the request, target port is 161 but source port differs, which is expected since it finds whatever available port at that moment. I also want to fix that port but do not know how to do it with pysnmp.hlapi. What I need is binding the port that is used to send SNMP over pysnmp. I googled it but could not find much so I am here.


Solution

  • Try calling .setLocalAddress on the hlapi.UdpTransportTarget object. That should make your end of the socket bound to this specific address.

    Perhaps it makes sense to keep that endpoint permanently allocated so that you won't bump into a busy port grabbed by some other process.