Search code examples
powershellsnmpsnmp-trap

Send SNMP trap with powershell script


I'm trying to send SNMP traps with a powershell script (it has to be a powershell script, it will be running on a windows server). I have a test enviroment running that has a trap reciever.

I've been following this tutorial http://www.activexperts.com/network-component/howto/snmpts/powershell10/ but I haven't gotten it to work.

Below is my code, the script is running fine

$objSnmpTrapManager = new-object -comobject AxNetwork.DnsServer #create object
# Create a SnmpTrapOut instance
$objSnmpTrapManager = new-object -comobject AxNetwork.SnmpTrapManager
$objSnmpTrap     = new-object -comobject AxNetwork.SnmpTrap
$objSnmpObject   = new-object -comobject AxNetwork.SnmpObject
$objConstants    = new-object -comobject AxNetwork.NwConstants

# Initialize SNMP
$objSnmpTrapManager.Initialize()
$res = "Initialize, result: " + $objSnmpTrapManager.LastError + " (" + $objSnmpTrapManager.GetErrorDescription( $objSnmpTrapManager.LastError ) + ")"
Write-Host $res
If($objSnmpTrapManager.LastError -ne 0 )
{
  exit
}

# Get Host, community name and optionally a MIB file
$strHostName    = "*******"
$strCommunity   = "public"

# Set trap properties
$objSnmpTrap.Clear()
$objSnmpTrap.Host     = $strHostName
$objSnmpTrap.Community = $strCommunity
$objSnmpTrap.Port     = 80 #is this the port that my trap reciever is looking at? or should it be the default 162

# Add first variable to trap
$objSnmpObject.Clear()
$objSnmpObject.OID   = ".1.3.6.1.2.1.1.5.0"
$objSnmpObject.Type  = $objConstants.nwSNMP_TYPE_OCTETSTRING
$objSnmpObject.Value = "test"
$objSnmpTrap.AddObject($objSnmpObject)

# Send the trap.
$objSnmpTrapManager.Send($objSnmpTrap)
$res = "Send, result: " + $objSnmpTrapManager.LastError + " (" + $objSnmpTrapManager.GetErrorDescription($objSnmpTrapManager.LastError) + ")"
Write-Host $res

# Shutdown SNMP
$objSnmpTrapManager.Shutdown()
$res = "Shutdown, result: " + $objSnmpTrapManager.LastError + " (" + $objSnmpTrapManager.GetErrorDescription($objSnmpTrapManager.LastError) + ")"
Write-Host $res  

Everything says success, I think my problem is defining the location of where to send my traps (if someone could provide an example that would be awesome!)

Does anyone have any help or resources they'd be willing to share?

Thanks!


Solution

  • The port ($objSnmpTrap.Port) should be 162, the default SNMP Trap receiver (or trapsink) port - unless you've explicitly changed that to port 80 in your test environment:

    # Get Host, community name and optionally a MIB file
    $strHostName    = "receiver.test.environment.example"
    $strCommunity   = "public"
    
    # Set trap properties
    $objSnmpTrap.Clear()
    $objSnmpTrap.Host     = $strHostName
    $objSnmpTrap.Community = $strCommunity
    $objSnmpTrap.Port = 162