# Sample Code : trapcmd.rb # # Run a command if you get a trap containing certain values # # You need to install Unbrowse SNMP and Ruby # --------------------------------------------------- require 'win32ole' #COMMAND_TO_RUN = %q(notepad.exe) COMMAND_TO_RUN = %q(mplay32.exe /play /close c:\Windows\Media\notify.wav) # --------------------------------------------------- # pr_trap ; Dumps all trap information onto screen # Helps in debugging # --------------------------------------------------- def pr_trap(one_trap) # -------------------------- # Print basic trap information # -------------------------- puts " ------------------------------------------" puts " Trap ID : #{one_trap.ID}" puts " From Agent : #{one_trap.AgentAddress}" puts " To Manager : #{one_trap.DestinationAddress}" puts " Timestamp : #{one_trap.TimestampLocal}" puts " User/Comm : #{one_trap.UserCommunity}" puts " Varbinds : #{one_trap.VarbindCount}" puts " OID : #{one_trap.TrapOID}" # -------------------------- # Print all varbinds in trap # -------------------------- puts " --------- Varbind list ----------" (0 .. one_trap.VarbindCount - 1).each do |i| one_varbind = one_trap.GetVarbindByIdx(i) puts "\t #{one_varbind.OID} = #{one_varbind.Value}" end puts " ------------------------------------------" end # --------------------------------------------------- # need_to_alert? examine all varbinds for # a OID (check_oid) containing a specific # value (check_val) # --------------------------------------------------- def need_to_alert?(one_trap, check_oid, check_val ) (0 .. one_trap.VarbindCount - 1).each do |i| one_varbind = one_trap.GetVarbindByIdx(i) if one_varbind.OID == check_oid and one_varbind.Value == check_val return true end end return false end # No arguments expected raise "USAGE: ruby #{$0}" unless ARGV.size == 0 # Create a trap recevier trap_mgr = WIN32OLE.new("UnbrowseSNMP.TrapReceiver") puts "Loaded the Unbrowse SNMP Trap Server" # Lets run in normal UDP mode (listing in port 162) # Default is Winpcap, you can also use UDPServerPort to change the port trap_mgr.UDPServerMode = true # Buffer database is used for infinitely running captures trap_mgr.NewBufferDatabase puts "Starting .." trap_mgr.Start puts "Listening for traps ... (Ctrl+C) to stop " last_processed = 0 # Loop : Get Traps > Print Trap (for debugging) > Check if matching > Run command while true trap_text = "" end_id = trap_mgr.TrapCount (last_processed..end_id-1).each do |tid| trp = trap_mgr.GetTrapByIdx(tid) pr_trap(trp) # we will launch notepad if any matching trap comes in # replace with your system(COMMAND_TO_RUN) if need_to_alert?(trp,".1.3.6.1.4.1.9.10.91.1.2.3.1.7","problem") trap_mgr.DeleteTrapByIdx(tid-1) end last_processed = end_id sleep(1) end puts "stopping the trap receiver" trap_mgr.Stop