Advertisement
Tlams

Easy_snmp_get

Feb 20th, 2013
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
AutoIt 27.08 KB | None | 0 0
  1. ;-----------------------------------------------------
  2. ; Cette première partie contient toutes les fonctions snmp ! Ne pas toucher.
  3. ; Pour la partie imprimante cf: Lignes 551  
  4. ;-----------------------------------------------------
  5. #include-once
  6. #Include <String.au3>
  7. #Include <Array.au3>
  8. #include <GUIConstantsEx.au3>
  9. #include <WindowsConstants.au3>
  10. #include <EditConstants.au3>
  11. #include <StaticConstants.au3>
  12. #include <Misc.au3>
  13. #include <sendmessage.au3>
  14. #include <Date.au3>
  15.  
  16. #NoEnv
  17. #SingleInstance Force
  18.  
  19. ;-----------------------------------------------------
  20. ;Credit for idea of this UDF and alot of work on it:    @ptrex
  21. ;Credit for fixing the version 1.7.3:   @nobur
  22. ;version 1.7.3-nobur - (12.09.2012)
  23. ;OID Arrays are no longer supported: they didn't add anything to UDF's value and were only complicating the scripts
  24. ;-----------------------------------------------------
  25. Const $SNMP_data_INT        = "02"
  26. Const $SNMP_data_STR        = "04"
  27. Const $SNMP_data_NULL       = "05"
  28. Const $SNMP_data_OID        = "06"
  29. Const $SNMP_data_SEQ        = "30"
  30. Const $SNMP_data_IP         = "40"
  31. Const $SNMP_data_COUNTER    = "41"
  32. Const $SNMP_data_GAUGE      = "42"
  33. Const $SNMP_data_TIME       = "43"
  34. Const $SNMP_data_COUNTER64  = "46"
  35.  
  36. Global $SNMP_Received[1500][3]
  37. Global $Varbind_content[1000]
  38. Global $SNMP_Util[1000][3]
  39.  
  40. #region ~~~~~~~~~~~~~~~~~~~~ BUILD SNMP Packet ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  41. ;===============================================================================
  42. ; Description:      Build SNMP Message
  43. ; Syntax:          _SNMPBuildPacket($snmpOID, $snmpCOMM, $snmpVER, $snmpReqID, $PDUType = "A1")
  44. ; Parameter(s):     $snmpOID - Object ID (OID) ex: "1.3.6.1.2.1.1.1"
  45. ;                   $snmpCOMM - Community String -> the default values are "public" for read-only and "private" for read-write
  46. ;                   $snmpVER - SNMP Version (3 versions available, 1, 2 and 3 - this UDF handles only SNMP v1 and v2c)
  47. ;                       1 = SNMP v1
  48. ;                       2 = SNMP v2c
  49. ;                       3 = SNMP v3 -> NOT WORKING
  50. ;                   $snmpReqID - Request ID - an Integer that identifies a particular SNMP request.
  51. ;                   $PDUType - PDU type ("A0"= GetRequest, "A1"= GetNext, "A2"= GetResponse, "A3"= SetRequest, "A5"= Get Bulk))
  52. ;                   $GetBulk - (hex) how many OIDs to return (50 MAXIMUM recommended) - if you request too many OIDs you will get an error.
  53. ;                   $dataTYPE - data TYPE to be written     (for SetRequest) - refer to "const" values at the top
  54. ;                   $dataVALUE - data VALUE to be written   (for SetRequest)
  55. ; Requirement(s):   Must be used from withing this UDF (calls other functions)
  56. ; Return Value(s):  On Success - Returns a hex string which is to be send
  57. ; Error Code:       1 = SNMP version error (GetBulk request used with SNMP v1)
  58. ;                   2 = wrong data type for SetRequest
  59. ;                   3 = $snmpOID is an array (arrays are no longer supported)
  60. ; Author(s):        enaiman <naimane at yahoo dot com>
  61. ; Note(s):          None
  62. ;===============================================================================
  63. Func _SNMPBuildPacket($snmpOID, $snmpCOMM = "public", $snmpVER = 1, $snmpReqID = 1, $PDUType = "A1", $GetBulk = "32", $dataTYPE = "05", $dataVALUE = "00")
  64. ;~~~~~~~~~~~~~~~~~~~~~~~~~~~ building the packet backwards ... ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  65.     _Init()                                                                     ;resets global variables
  66. ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  67.     If IsArray($snmpOID) Then
  68.         MsgBox(16, "OID Array", "OID Arrays are no longer supported.")
  69.         Return SetError(3)
  70.     EndIf
  71.     Switch $snmpVER
  72.         Case 1,2
  73.             $_SNMP_Req_Varbind  = _Build_Varbind    ($snmpOID, $dataTYPE, $dataVALUE)
  74.             If @error Then
  75.                 MsgBox(16, "Unknown Data Type", "Unknown Data Type: "&$dataTYPE)
  76.                 Return SetError(2)
  77.             EndIf
  78.             If $PDUType = "A5" And $snmpVER = 1 Then
  79.                 MsgBox(16, "Wrong SNMP Version", "GetBulk request cannot be used with SNMP v1.")
  80.                 Return SetError(1)
  81.             EndIf
  82.             $_SNMP_Req_PDU      = _Build_PDU        ($snmpReqID, $PDUType, $GetBulk, $_SNMP_Req_Varbind)
  83.             $_SNMP_Req_Message  = _Build_Message    ($snmpVER, $snmpCOMM, $_SNMP_Req_PDU)
  84.             _WriteArrayValues($SNMP_Received, 1, "SNMP Command", $_SNMP_Req_Message)
  85.             Return $_SNMP_Req_Message
  86.         Case 3
  87.             MsgBox(16, "SNMP v3 Not Supported", "SNMP v3 is not supported yet.")
  88.             Return SetError(1)
  89.         Case Else
  90.             MsgBox(16, "Wrong SNMP Version", "Unknown SNMP Version: "&$snmpVER)
  91.             Return SetError(1)
  92.     EndSwitch
  93. EndFunc
  94. #endregion
  95. #region ~~~~~~~~~~~~~~~~~~~~ EXTRACT SNMP Data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  96. ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  97. ;Returned Data in is 2 Arrays
  98. ;$SNMP_Received = Contains a more detailed range of data (educational purpose)
  99. ;   << NEW >> - now $SNMP_Received has an extra row, showing raw data for each PDU (delimited string)
  100. ;$SNMP_Util     = Util information received:
  101. ;       $SNMP_Util[0][0] = "Error Code"
  102. ;       $SNMP_Util[0][1] = error value
  103. ;       $SNMP_Util[1][0] = OID
  104. ;       $SNMP_Util[1][1] = Value read from OID
  105. ;   If more that 1x OID were requested then the next results will be added
  106. ;       $SNMP_Util[2][0] = OID
  107. ;       $SNMP_Util[2][1] = Value read from OID
  108. ;~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  109. Func _ShowSNMPReceived($rcvDATA)
  110.     Global $SNMP_Util[1000][3]
  111.     Local $_sPacketRecv_ = $rcvDATA
  112.     Local $_PDUcontent      = ""
  113.     Local $_ExtractedDATA
  114.     Local $_IsError = 0
  115.     Local $_PDU_content = ""
  116.     Local $_delimSTR_ = ""
  117.     _WriteArrayValues($SNMP_Received, 1, "SNMP Answer", $rcvDATA)
  118.     $rcvDATA = StringTrimLeft($rcvDATA, 4)          ;strip 0x30
  119.     Local $_l_pl = _GetPacLen_(StringLeft($rcvDATA, 6))
  120.     Local $_pacLen_ = StringLeft($rcvDATA, $_l_pl)
  121.     $rcvDATA = StringTrimLeft($rcvDATA, $_l_pl) ;strip packet length
  122.     _WriteArrayValues($SNMP_Received, 2, "(Total) PDU Length", $_pacLen_)
  123. ;------------- SNMP Version Block -------------------------------------------------
  124.     _WriteArrayValues($SNMP_Received, 3, "SNMP Version Block", StringLeft($rcvDATA, 6))
  125.     $rcvDATA = StringTrimLeft($rcvDATA, 4)          ;strip 0201 from SNMP ver block
  126.     Local $_snmpV_ = StringLeft($rcvDATA, 2)+1              ;SNMP Version
  127.     $rcvDATA = StringTrimLeft($rcvDATA, 2)          ;strip SNMP Version
  128. ;------------- Community String ---------------------------------------------------
  129.     $rcvDATA = StringTrimLeft($rcvDATA, 2)          ;strip 04 from community block
  130.     Local $_commLen_ = Dec(StringLeft($rcvDATA, 2))*2       ;Length of community string
  131.     $rcvDATA = StringTrimLeft($rcvDATA, 2)          ;strip community length
  132.     Local $_commHex_ = StringLeft($rcvDATA, $_commLen_) ;community string (hex)
  133.     Local $_commTex_ = _HexToString($_commHex_)
  134.     $rcvDATA = StringTrimLeft($rcvDATA, $_commLen_)
  135.     _WriteArrayValues($SNMP_Received, 4, "Community String", $_commTex_)
  136. ;------------- PDU Type -----------------------------------------------------------
  137.     Local $_pduT_ = StringLeft($rcvDATA, 2)
  138.     _WriteArrayValues($SNMP_Received, 5, "PDU Type", $_pduT_)
  139.     $rcvDATA = StringTrimLeft($rcvDATA, 2)
  140.     $rcvDATA = _StripPacket($rcvDATA)
  141. ;------------- Request ID ---------------------------------------------------------
  142.     $rcvDATA = _StripBlocks($rcvDATA, 6, "Request ID Block")
  143. ;------------- Error Block --------------------------------------------------------
  144.     Local $_sErr_ = StringMid($rcvDATA, 5, 2)
  145.     If $_sErr_ <> "00" Then
  146.         _ThrowError($_sErr_, $_sPacketRecv_)
  147.         Return SetError(1)
  148.     EndIf
  149.     _WriteArrayValues($SNMP_Util, 0, "SNMP Error Value:", $_sErr_)
  150.     $rcvDATA = _StripBlocks($rcvDATA, 7, "Error Block")
  151. ;------------- Error Index --------------------------------------------------------
  152.     $rcvDATA = _StripBlocks($rcvDATA, 8, "Error Index Block")
  153. ;------------- PDU Total Len ------------------------------------------------------
  154.     $rcvDATA = StringTrimLeft($rcvDATA, 2)
  155.     $_l_pl = _GetPacLen_(StringLeft($rcvDATA, 6))
  156.     Local $_pacTotLen_ = StringLeft($rcvDATA, $_l_pl)
  157.     $rcvDATA = StringTrimLeft($rcvDATA, $_l_pl)                     ;strip packet length
  158. ;------------- PDU Data -----------------------------------------------------------
  159.     Local $_snmpR_idx = 9, $_snmpA_idx = 1
  160.     Do
  161.         $rcvDATA = StringTrimLeft($rcvDATA, 2)                              ;cut "30" (data type: SEQ)
  162.         $_l_pl = _GetPacLen_(StringLeft($rcvDATA, 6))                       ;length of Data PDU
  163.         $_pacLen_ = StringLeft($rcvDATA, $_l_pl)
  164.         $rcvDATA = StringTrimLeft($rcvDATA, $_l_pl)                         ;cut length
  165.         $_PDU_content = StringLeft($rcvDATA, Dec($_pacLen_)*2)              ;get what is left from PDU
  166.         $rcvDATA = StringTrimLeft($rcvDATA, Dec($_pacLen_)*2)               ;remove that from message
  167.         $_delimSTR_ = "30|"&$_pacLen_&"|"                                   ;build delimited string
  168.         If StringLeft($_PDU_content, 2) = "06" Then
  169.             $_delimSTR_ &= "06|"
  170.             $_PDU_content = StringTrimLeft($_PDU_content, 2)                ;cut "06" (data type: OID)
  171.             $_l_pl = _GetPacLen_(StringLeft($_PDU_content, 6))              ;Length of OID sequence
  172.             $_pacLen_ = StringLeft($_PDU_content, $_l_pl)
  173.             $_PDU_content = StringTrimLeft($_PDU_content, $_l_pl)           ;cut length
  174.             Local $_OID_val = StringLeft($_PDU_content, Dec($_pacLen_)*2)   ;OID (hex)
  175.             $_delimSTR_ &= $_pacLen_&"|"&$_OID_val&"|"
  176.             Local $_Decoded_OID = _TranslateOID($_OID_val, "2d")            ;OID (dec)
  177.             $_PDU_content = StringTrimLeft($_PDU_content, Dec($_pacLen_)*2)
  178.             Local $_data_type = StringLeft($_PDU_content, 2)                ;returned data type
  179.             $_PDU_content = StringTrimLeft($_PDU_content, 2)
  180.             If StringLen($_PDU_content) >= 6 Then
  181.                 $_l_pl = _GetPacLen_(StringLeft($_PDU_content, 6))              ;Length of data sequence
  182.             Else
  183.                 $_l_pl = _GetPacLen_(StringLeft($_PDU_content, 4))              ;Length of data sequence
  184.             EndIf
  185.             Local $_raw_data = StringTrimLeft($_PDU_content, $_l_pl)
  186.             Local $_RealData = _ExtractData($_data_type, $_raw_data)
  187.             _WriteArrayValues($SNMP_Received, $_snmpR_idx, $_Decoded_OID, $_RealData)
  188.             $_snmpR_idx += 1
  189.             $_delimSTR_ &= $_data_type&"|"&StringLeft($_PDU_content, $_l_pl)&"|"&$_raw_data
  190.             _WriteArrayValues($SNMP_Received, $_snmpR_idx, "Raw PDU (delimited string)", $_delimSTR_)
  191.             $_snmpR_idx += 1
  192.             _WriteArrayValues($SNMP_Util, $_snmpA_idx, $_Decoded_OID, $_RealData)
  193.             $_snmpA_idx += 1
  194.             $_delimSTR_ = ""
  195.         Else
  196.             Return SetError(2)      ;bad SNMP Packet
  197.         EndIf
  198.     Until Int(StringLen($rcvDATA)) = 0
  199.     ReDim $SNMP_Received[$_snmpR_idx][3]
  200.     ReDim $SNMP_Util[$_snmpA_idx][3]
  201.     Return $SNMP_Util
  202. EndFunc     ;==>_ShowSNMPReceived
  203. #endregion
  204. #region ~~~~~~~~~~~~~~~~~~~~ Add Packet Layers ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  205. Func _Build_Varbind($p_OID, $p_dTYPE, $p_dVALUE)
  206.     Local $_result_
  207.     Local $oidarr
  208.     Switch $p_dTYPE
  209.         Case $SNMP_data_INT, $SNMP_data_COUNTER, $SNMP_data_GAUGE, $SNMP_data_TIME
  210.             $p_dVALUE = Hex($p_dVALUE, 8)
  211.             For $_j = 1 To 3
  212.                 If StringLeft($p_dVALUE, 2) = "00" Then
  213.                     $p_dVALUE = StringTrimLeft($p_dVALUE, 2)
  214.                 EndIf
  215.             Next
  216.         Case $SNMP_data_STR                                                             ;STR
  217.             $p_dVALUE = _StringToHex($p_dVALUE)
  218.         Case $SNMP_data_NULL                                                            ;NULL
  219.             $p_dVALUE = "00"
  220.         Case $SNMP_data_OID                                                             ;OID
  221.             $p_dVALUE = _TranslateOID($p_dVALUE, "2h")
  222.         Case $SNMP_data_IP                                                              ;IP
  223.             $p_dVALUE = _SNMPEncodeIP($p_dVALUE)
  224.         Case Else
  225.             Return SetError(1)
  226.     EndSwitch
  227.     Local $_sl_ = Int(StringLen($p_dVALUE)/2)
  228.     Local $_p_dLen = Hex($_sl_,2)
  229.     if Number($p_dTYPE)=05 then
  230.         $_result_ = $p_dTYPE & "00"         ;if null send null data type and  null data value
  231.     Else
  232.         $_result_ = $p_dTYPE & $_p_dLen & $p_dVALUE    ;if not null, send data type, data lenght and data value
  233.     EndIf
  234.     $oidarr = _TranslateOID($p_OID, "2h")
  235.     $_result_ = $oidarr & $_result_
  236.     $_result_ = Hex(Int(StringLen($_result_)/2),2) & $_result_
  237.     $_result_ = $SNMP_data_SEQ & $_result_
  238.     $_result_ = Hex(Int(StringLen($_result_)/2),2) & $_result_
  239.     $_result_ = $SNMP_data_SEQ & $_result_
  240.     Return $_result_
  241. EndFunc
  242. Func _Build_PDU($p_ReqID, $p_PDUType, $p_bulk, $p_varbind)
  243.     Local $_result_
  244.     $_result_ = $p_varbind
  245.     If $p_PDUType = "A5" Then                               ;error Index
  246.         $_result_ = "0201" & $p_bulk & $_result_
  247.     Else
  248.         $_result_ = "020100" & $_result_
  249.     EndIf
  250.     $_result_ = "020100" & $_result_                        ;error
  251.     $_result_ = "020200" & Hex($p_ReqID, 2) & $_result_     ;request ID
  252.     $_result_ = Hex(Int(StringLen($_result_)/2),2) & $_result_
  253.     $_result_ = $p_PDUType & $_result_
  254.     Return $_result_
  255. EndFunc
  256. Func _Build_Message($p_VER, $p_COMM, $p_PDU)
  257.     Local $_result_
  258.     $_result_ = $p_PDU
  259.     $_result_ = _BuildCOM_($p_COMM) & $_result_
  260.     $_result_ = "0201" & Hex($p_VER-1, 2) & $_result_
  261.     $_result_ = Hex(Int(StringLen($_result_)/2),2) & $_result_
  262.     $_result_ = "0x" & $SNMP_data_SEQ & $_result_
  263.     Return $_result_
  264. EndFunc
  265. Func _TranslateOID($input, $dir)
  266.     Local $l_OID = ""
  267.     Switch $dir
  268.         Case "2d"
  269.             Local $_dex_OID = _SNMPExtractOID($input)
  270.             Return $_dex_OID
  271.         Case "2h"
  272.             Local $hex_OID = _SysObjIDToHexString($input)           ;transform the OID in a hex value
  273.             $hex_OID = "2B" & $hex_OID                              ;add "2B" in front of the string
  274.             Local $len_OID = Hex(Int(StringLen($hex_OID)/2), 2)         ;calculate the length
  275.             $l_OID = $SNMP_data_OID                                 ;1st element Object ID = ASN.1 type "06"
  276.             $l_OID &= $len_OID                                      ;2nd element = length
  277.             $l_OID &= $hex_OID
  278.             Return $l_OID
  279.     EndSwitch
  280. EndFunc
  281. Func _BuildCOM_($comm)
  282.     Local $hex_COMM = _StringToHex($comm)                   ;transform the community string in a hex value
  283.     Local $len_COMM = Hex(Int(StringLen($hex_COMM)/2), 2)       ;calculate the length
  284.     Local $_comm_ = "04"& $len_COMM & $hex_COMM
  285.     Return $_comm_
  286. EndFunc     ;==>_BuildCOM_
  287. Func _GetPacLen_($sPkt)
  288.     Local $pacl = 0
  289.     Switch StringLeft($sPkt, 2)
  290.         Case "81"
  291.             $pacl = 4
  292.         Case "82"
  293.             $pacl = 6
  294.         Case Else
  295.             $pacl = 2
  296.     EndSwitch
  297.     Return $pacl
  298. EndFunc
  299. Func _StripPacket($spkt)
  300.     Local $_l_pl = _GetPacLen_(StringLeft($spkt, 6))
  301.     Local $_pacLen_ = StringLeft($spkt, $_l_pl)
  302.     $spkt = StringTrimLeft($spkt, $_l_pl)   ;strip packet length
  303.     Return $spkt
  304. EndFunc
  305. Func _StripBlocks($spkt, $_el, $_eltxt)
  306.     Select
  307.         Case StringLeft($spkt, 4) = "0202"
  308.             _WriteArrayValues($SNMP_Received, $_el, $_eltxt, StringLeft($spkt, 8))
  309.             $spkt = StringTrimLeft($spkt, 8)
  310.         Case StringLeft($spkt, 4) = "0201"
  311.             _WriteArrayValues($SNMP_Received, $_el, $_eltxt, StringLeft($spkt, 6))
  312.             $spkt = StringTrimLeft($spkt, 6)
  313.     EndSelect
  314.     Return $spkt
  315. EndFunc
  316. #endregion
  317. #region ~~~~~~~~~~~~~~~~~~~~ Encode IP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  318. Func _SNMPEncodeIP($strIP)
  319.     Local $encoded_IP = ""
  320.     Local $encoded_IParr
  321.     $encoded_IParr = StringSplit($strIP, ".")
  322.     If $encoded_IParr[0] <> 4 Then
  323.         ConsoleWrite("ERROR: Wrong IP Format "&$strIP&@CRLF)
  324.         Return SetError(1)
  325.     EndIf
  326.     $encoded_IP = Hex($encoded_IParr[1], 2)&Hex($encoded_IParr[2], 2)&Hex($encoded_IParr[3], 2)&Hex($encoded_IParr[4], 2)
  327.     Return $encoded_IP
  328. EndFunc     ;==>_SNMPEncodeIP
  329. #endregion ~~~~~~~~~~~~~~~~~ END Encode IP ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  330. #region ~~~~~~~~~~~~~~~~~~~~ Encode OID ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  331. Func _BuildOID($oid)
  332.     Local $hex_OID = _SysObjIDToHexString($oid)             ;transform the OID in a hex value
  333.     $SNMP_hexOID = $hex_OID
  334.     $hex_OID = "2B" & $hex_OID                              ;add "2B" in front of the string
  335.     Local $len_OID = Hex(Int(StringLen($hex_OID)/2), 2)         ;calculate the length
  336.     Local $OID_Arr[Dec($len_OID) + 2]                       ;build array to store values
  337.     $OID_Arr[0] = $SNMP_data_OID                            ;1st element Object ID = ASN.1 type "06"
  338.     $OID_Arr[1] = $len_OID                                  ;2nd element = length
  339.     For $i = 2 To Dec($len_OID)+1                           ;2digit OID parts
  340.         $OID_Arr[$i] = StringMid($hex_OID, 2*$i - 3, 2)
  341.     Next
  342.     Return $OID_Arr
  343. EndFunc     ;==>_BuildOID
  344. Func _SysObjIDToHexString($Input)                           ;convert OID to hex form
  345.     Local $Output
  346.     If StringLeft($Input,4) = "1.3." Then $Input = StringTrimLeft($Input,4)
  347.     $aInput = StringSplit($Input,".")
  348.     For $x = 1 To $aInput[0]
  349.         If Number($aInput[$x]) > 127 Then
  350.             $Output &= _encode(Number($aInput[$x]))
  351.         Else
  352.             $Output &= hex(Number($aInput[$x]),2)
  353.         EndIf
  354.     Next
  355.     Return $Output
  356. EndFunc     ;==>_SysObjIDToHexString
  357. Func _encode($d, $r = 0)
  358.     $Op_Result = ""
  359.     $t1 = Int($d / 128)
  360.     $t2 = Int($d - $t1 * 128)
  361.     If $t1 Then $Op_Result &= _encode($t1, 1)
  362.     If $r Then $t2 += 128
  363.     $Op_Result &= Hex($t2, 2)
  364.     Return $Op_Result
  365. EndFunc   ;==>_encode
  366. #endregion ~~~~~~~~~~~~~ END Encode OID ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  367. #region ~~~~~~~~~~~~~~~~~~~~ Initialize Variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  368. Func _Init()
  369.     Dim $SNMP_Received[1500][3]
  370.     Dim $Varbind_content[1000]
  371.     Dim $SNMP_Util[1000][3]
  372. EndFunc
  373. #endregion ~~~~~~~~~~~~~~~~ END Initialize Variables ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  374. #region ~~~~~~~~~~~~~~~~~~~~ MISC Functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  375. ;memo: improve _DeleteIndexes - it takes too long to delete/redim the array everytime !!!
  376. Func _ExtractData($dtype, $tmpOUT)                                      ;Extract clear data
  377.     Switch $dtype
  378.         Case "04"           ;string
  379.             Return BinaryToString("0x"&$tmpOUT)
  380.         Case "02"           ;number
  381.             Return _SNMPHexToDec ($tmpOUT)
  382.         Case "06"           ;OID
  383.             Return _SNMPExtractOID($tmpOUT)
  384.         Case "40"           ;IP Address
  385.             Return _SNMPExtractIP ($tmpOUT)
  386.         Case "41"           ;Counter
  387.             Return _SNMPHexToDec ($tmpOUT)
  388.         Case "42"           ;Gauge
  389.             Return _SNMPHexToDec ($tmpOUT)
  390.         Case "43"
  391.             Return _SNMPHexToDec($tmpOUT)/100 &" sec."
  392.         Case "46"           ;Counter64
  393.             Return _SNMPHexToDec ($tmpOUT)
  394.     EndSwitch
  395. EndFunc     ;==>_ExtractData
  396. Func _SNMPExtractIP($strIP)
  397.     Local $extractedIParray [5]
  398.     Local $extractedIP = ""
  399.     For $i = 1 To 4
  400.         $extractedIParray[$i] = Dec(StringMid($strIP, 2*$i - 1, 2))
  401.         If $i = 4 Then
  402.             $extractedIP &= $extractedIParray[$i]
  403.         Else
  404.             $extractedIP &= $extractedIParray[$i] & "."
  405.         EndIf
  406.     Next
  407.     Return $extractedIP
  408. EndFunc     ;==>_SNMPExtractIP
  409. Func _SNMPExtractOID($strOID)
  410.     Local $extractedOIDarray [StringLen($strOID)/2 + 1]
  411.     Local $extractedOID = "1.3."
  412.     For $i = 2 To StringLen($strOID)/2
  413.         Local $OIDtoDecode=""
  414.         $extractedOIDarray[$i] = StringMid($strOID, 2*$i - 1, 2)
  415.         If Dec($extractedOIDarray[$i]) > 128 Then
  416.             $OIDtoDecode &=$extractedOIDarray[$i]
  417.             $aA=0
  418.             While dec(StringMid($strOID, 2*($i + $aA)-1, 2))>128
  419.                 $OIDtoDecode &=" + "&StringMid($strOID, 2*($i + $aA)+1, 2)
  420.                 $aA+=1
  421.             WEnd
  422.             $extractedOID &= _decode($OIDtoDecode)
  423.             $i += $aA
  424.         Else
  425.             $extractedOID &= Dec($extractedOIDarray[$i])
  426.         EndIf
  427.         If $i < StringLen($strOID)/2 Then
  428.             $extractedOID &="."
  429.         EndIf
  430.     Next
  431.     Return $extractedOID
  432. EndFunc     ;==>_SNMPExtractOID
  433. Func _SNMPHexToDec ($nbr)
  434.     Local $extractedHEXarray [StringLen($nbr) + 1]
  435.     Local $extractedNBR = 0
  436.     For $i = 1 To StringLen($nbr)
  437.         $extractedHEXarray[$i] = StringMid($nbr, $i, 1)
  438.         $extractedNBR += 16^(StringLen($nbr)- $i)*Dec($extractedHEXarray[$i])
  439.     Next
  440.     Return $extractedNBR
  441. EndFunc     ;==>_SNMPHexToDec
  442. Func _decode($s, $d = 0)
  443.     $a = StringSplit($s, " + ", 1)
  444.     For $j = 1 To $a[0]
  445.         $d1 = Dec($a[$j])
  446.         If $d1 > 127 Then $d1 = $d1 - 128
  447.         $d = ($d * 128) + $d1
  448.     Next
  449.     Return $d
  450. EndFunc   ;==>_decode
  451. Func _WriteArrayValues(ByRef $ArrRet, $idx, $val0, $val1, $val2 = "")               ;write entries in returned arrays
  452.     ;_ArrayDisplay($ArrRet)
  453.     $ArrRet[$idx][0] = $val0
  454.     $ArrRet[$idx][1] = $val1
  455.     If $val2 <> "" Then $ArrRet[$idx][2] = $val2
  456. EndFunc     ;==>_WriteArrayValues
  457. Func _ThrowError($sErr, $spkt)
  458.     Switch $sErr
  459.         Case "00"
  460.             Return
  461.         Case "01"
  462.             ClipPut($spkt)
  463.             MsgBox(16, "SNMP Error Code: 1", "Error Message:  Response message too large to transport."&@CRLF&@CRLF&"                (packet received placed in clipboard)")
  464.         Case "02"
  465.             ClipPut($spkt)
  466.             MsgBox(16, "SNMP Error Code: 2", "Error Message:   The name of the requested object was not found."&@CRLF&@CRLF&"                (packet received placed in clipboard)")
  467.         Case "03"
  468.             ClipPut($spkt)
  469.             MsgBox(16, "SNMP Error Code: 3", "Error Message:   A data type in the request did not match the data type in the SNMP agent."&@CRLF&@CRLF&"                (packet received placed in clipboard)")
  470.         Case "04"
  471.             ClipPut($spkt)
  472.             MsgBox(16, "SNMP Error Code: 4", "Error Message:    The SNMP manager attempted to set a read-only parameter."&@CRLF&@CRLF&"                (packet received placed in clipboard)")
  473.         Case "05"
  474.             ClipPut($spkt)
  475.             MsgBox(16, "SNMP Error Code: 5", "Error Message:   General Error (some error other than the ones listed above)."&@CRLF&@CRLF&"                (packet received placed in clipboard)")
  476.         Case Else
  477.             ClipPut($spkt)
  478.             MsgBox(16, "SNMP Error Code: "&$spkt, "Error Message:   No Error message for this one."&@CRLF&@CRLF&"                (packet received placed in clipboard)")
  479.     EndSwitch
  480.     Exit
  481. EndFunc
  482. #cs
  483. 0
  484.  noError
  485.  No error occurred. This code is also used in all request PDUs, since they have no error status to report.
  486.  
  487. 1
  488.  tooBig
  489.  The size of the Response-PDU would be too large to transport.
  490.  
  491. 2
  492.  noSuchName
  493.  The name of a requested object was not found.
  494.  
  495. 3
  496.  badValue
  497.  A value in the request didn't match the structure that the recipient of the request had for the object. For example, an object in the request was specified with an incorrect length or type.
  498.  
  499. 4
  500.  readOnly
  501.  An attempt was made to set a variable that has an Access value indicating that it is read-only.
  502.  
  503. 5
  504.  genErr
  505.  An error occurred other than one indicated by a more specific error code in this table.
  506.  
  507. 6
  508.  noAccess
  509.  Access was denied to the object for security reasons.
  510.  
  511. 7
  512.  wrongType
  513.  The object type in a variable binding is incorrect for the object.
  514.  
  515. 8
  516.  wrongLength
  517.  A variable binding specifies a length incorrect for the object.
  518.  
  519. 9
  520.  wrongEncoding
  521.  A variable binding specifies an encoding incorrect for the object.
  522.  
  523. 10
  524.  wrongValue
  525.  The value given in a variable binding is not possible for the object.
  526.  
  527. 11
  528.  noCreation
  529.  A specified variable does not exist and cannot be created.
  530.  
  531. 12
  532.  inconsistentValue
  533.  A variable binding specifies a value that could be held by the variable but cannot be assigned to it at this time.
  534.  
  535. 13
  536.  resourceUnavailable
  537.  An attempt to set a variable required a resource that is not available.
  538.  
  539. 14
  540.  commitFailed
  541.  An attempt to set a particular variable failed.
  542.  
  543. 15
  544.  undoFailed
  545.  An attempt to set a particular variable as part of a group of variables failed, and the attempt to then undo the setting of other variables was not successful.
  546.  
  547. 16
  548.  authorizationError
  549.  A problem occurred in authorization.
  550.  
  551. 17
  552.  notWritable
  553.  The variable cannot be written or created.
  554.  
  555. 18
  556.  inconsistentName
  557.  The name in a variable binding specifies a variable that does not exist
  558.  
  559. #ce
  560.  
  561.  
  562. ;*******************
  563. ;**DEBUT DU SCRIPT**
  564. ;*******************
  565.  
  566. ;Auteur: Tlams
  567. ;Date: 18/02/13
  568. ;Fonction: Retourne le nombre de page imprimés par imprimantes.
  569. ;Language: AutoIt V3
  570. ;Programme version: 1.0
  571.  
  572.  
  573.  
  574.  
  575. ;~ *************** Paramettres ***************
  576.  
  577. Global $file_ip_list =  FileRead ("imp_iplist.txt")
  578. Global $conf_OID =  IniRead("easy_snmp_get.ini", "section1", "conf_OID", "1.3.6.1.2.1.43.10.2.1.4")
  579. Global $conf_start =  IniRead("easy_snmp_get.ini", "section1", "conf_start", "0")
  580. Global $log = " --->Informations<---" & @CRLF & "Auteur:Tlams" & @CRLF & "Date: 18/02/13" & @CRLF & "Contact:[email protected]" & @CRLF & "Language: AutoIt(v3)" & @CRLF & "Program.Version: 1.0" & @CRLF & " --->LOG START<---"
  581. Global $Port = IniRead("easy_snmp_get.ini", "section1", "Port", "161")                         
  582. Global $SNMP_Version = IniRead("easy_snmp_get.ini", "section1", "SNMP_Version", "2")                   
  583. Global $SNMP_Community = IniRead("easy_snmp_get.ini", "section1", "SNMP_Community", "public")          
  584. Global $SNMP_ReqID = 1
  585. Global $SNMP_Command
  586. Global $Start = 1
  587. Global $result
  588.  
  589. ;~ ***************  Exécution!  ***************
  590. if $conf_start = 0 then
  591.     GUICreate("EASY SNMP GET")
  592.     GUICtrlCreateLabel("Rentrez la liste des IPs, une en dessous de l'autre!", 15, 5)
  593.     $listedesip = GUICtrlCreateEdit($file_ip_list , 15, 20, 370, 190)
  594.     $log = GUICtrlCreateEdit($log , 15, 220, 370, 80, BitOR($WS_VSCROLL, $ES_AUTOVSCROLL, $ES_READONLY))
  595.     GUICtrlCreateLabel("L'OID:", 15, 305)
  596.     $OID = GUICtrlCreateInput ( $conf_OID, 15, 320 , 370 , 20)
  597.     $Button_1 = GUICtrlCreateButton("Lancer !", 15, 345,370)
  598.     $Button_2 = GUICtrlCreateButton("Aide", 15, 370,185)
  599.     $Button_3 = GUICtrlCreateButton("Quitter", 200, 370,185)
  600.     GUISetState()
  601.     Send("{END}")
  602. EndIf
  603.  
  604. While 1
  605.      if $conf_start = 0 then
  606.         $msg = GUIGetMsg()
  607.      else
  608.         local $msg
  609.         local $Button_1
  610.         local $Button_2
  611.         local $Button_3
  612.      EndIf
  613.      
  614.     if $msg = $GUI_EVENT_CLOSE then
  615.         Exit
  616.     elseif $msg = $Button_1 or $conf_start <> 0 then   
  617.         if $conf_start = 0 then
  618.            Global $SNMP_OID =  GUICtrlRead($OID)    
  619.            $file_ip = FileOpen("imp_iplist.txt", 2)
  620.            FileWrite($file_ip, GUICtrlRead($listedesip))
  621.            fileclose ($file_ip)
  622.            IniWrite ("easy_snmp_get.ini", "section1", "conf_OID", $SNMP_OID )
  623.          else
  624.             Global $SNMP_OID = IniRead("easy_snmp_get.ini", "section1", "conf_OID", "1.3.6.1.2.1.43.10.2.1.4")
  625.        EndIf
  626.        
  627.        $file_ip = FileOpen("imp_iplist.txt", 0)  
  628.        $date = @MDAY &"_"& @MON &"_"& @YEAR &"_"& @HOUR &"h"& @MIN &"m"& @SEC &"s"   
  629.        $file = FileOpen("Resultat_"& $date &".csv" , 2)
  630.        
  631.        UDPStartUp()
  632.        While 1
  633.           $dest_IP = FileReadLine($file_ip)
  634.           If @error = -1 Then
  635.             GUICtrlSetData($log,  @CRLF & "Fin du fichier", 1)
  636.             ExitLoop
  637.           EndIf
  638.          
  639.           if $dest_IP <> "" then     
  640.               $var = Ping($dest_IP, 1500)
  641.               If $var Then
  642.                  $Socket = UDPopen($dest_IP, $Port)  
  643.                  $SNMP_Command = _SNMPBuildPacket($SNMP_OID, $SNMP_Community,$SNMP_Version, $SNMP_ReqID, "A1")
  644.                  UDPSend($Socket, $SNMP_Command)
  645.                     If $Start = 1 Then
  646.                       While 1
  647.                           $srcv = UDPRecv($Socket, 2048)
  648.                           If ($srcv <> "") Then
  649.                               $result = _ShowSNMPReceived ($srcv)
  650.                               ConsoleWrite($srcv &@CRLF)
  651.                               FileWriteLine($file,$dest_IP & ";" & $result[1][1])
  652.                               GUICtrlSetData($log,  @CRLF & "Résultat trouvé pour:" & $dest_IP & ":" & $result[1][1], 1)
  653.                              ExitLoop
  654.                           EndIf
  655.                       WEnd
  656.                   UDPCloseSocket($Socket)
  657.                   EndIf
  658.                Else
  659.                   GUICtrlSetData($log,  @CRLF & "Erreur pour:" & $dest_IP & "(" & @error & ")", 1)     
  660.                   FileWriteLine($file,$dest_IP & ";" & "#Erreur")
  661.               EndIf
  662.          EndIf
  663.        WEnd            
  664.        UDPShutdown()
  665.        GUICtrlSetData($log,  @CRLF & "Ecriture des résultats dans: Resultat_"& $date &".csv", 1)
  666.        FileClose("Resultat_"& $date &".csv")
  667.        GUICtrlSetData($log,  @CRLF & "Terminé", 1)    
  668.        if $conf_start <> 0 then
  669.             exit
  670.         EndIf
  671.     elseif $msg = $Button_2 then
  672.      MsgBox(0,"Aide", "Il est possible de l’utiliser sans interface graphique." & @CRLF &  "Pour cela : " & @CRLF & "- Editer / créer le fichier « imp_iplist.txt » contenant la liste des IPs une en dessous de l’autre." & @CRLF & "- Editer / créer le fichier « easy_snmp_get.ini » qui devra contenir les lignes suivantes : " & @CRLF & "[section1]" & @CRLF & "conf_OID=VOTRE OID" & @CRLF & "conf_start = 1 " & @CRLF & @CRLF &  "Pour repasser en interface graphique il suffit de supprimer la ligne 'conf_start = 1' ou de passer sa valeur à 0." & @CRLF &  @CRLF &"-------------------------------" & @CRLF &  @CRLF & "Autres paramettres possibles:" & @CRLF & "SNMP_Version = 2 (Par défaut)" & @CRLF & "SNMP_Community = public (Par défaut)" & @CRLF & "Port = 161 (Par défaut)" & @CRLF & @CRLF & "-------------------------------" & @CRLF & @CRLF & "Liste des erreurs:" & @CRLF & "1 = L'hote est hors ligne" & @CRLF & "2 = L'hote est introuvable" & @CRLF & "3 = Mauvaise destination" & @CRLF & "4 = Autres erreurs")  
  673.     elseif $msg = $Button_3 then
  674.        exit
  675.     EndIf
  676. WEnd
  677. GUIDelete()
  678. exit
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement