⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 snmpsend.pas

📁 snmp设计增加相应SNMP的OID,是实时处理的.
💻 PAS
📖 第 1 页 / 共 3 页
字号:
{==============================================================================|
| Project : Ararat Synapse                                       | 003.000.007 |
|==============================================================================|
| Content: SNMP client                                                         |
|==============================================================================|
| Copyright (c)1999-2004, Lukas Gebauer                                        |
| All rights reserved.                                                         |
|                                                                              |
| Redistribution and use in source and binary forms, with or without           |
| modification, are permitted provided that the following conditions are met:  |
|                                                                              |
| Redistributions of source code must retain the above copyright notice, this  |
| list of conditions and the following disclaimer.                             |
|                                                                              |
| Redistributions in binary form must reproduce the above copyright notice,    |
| this list of conditions and the following disclaimer in the documentation    |
| and/or other materials provided with the distribution.                       |
|                                                                              |
| Neither the name of Lukas Gebauer nor the names of its contributors may      |
| be used to endorse or promote products derived from this software without    |
| specific prior written permission.                                           |
|                                                                              |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"  |
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE    |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE   |
| ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR  |
| ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL       |
| DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR   |
| SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER   |
| CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT           |
| LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY    |
| OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH  |
| DAMAGE.                                                                      |
|==============================================================================|
| The Initial Developer of the Original Code is Lukas Gebauer (Czech Republic).|
| Portions created by Lukas Gebauer are Copyright (c)2000-2004.                |
| All Rights Reserved.                                                         |
|==============================================================================|
| Contributor(s):                                                              |
|   Jean-Fabien Connault (cycocrew@worldnet.fr)                                |
|==============================================================================|
| History: see HISTORY.HTM from distribution package                           |
|          (Found at URL: http://www.ararat.cz/synapse/)                       |
|==============================================================================}

{:@abstract(SNMP client)
Supports SNMPv1 include traps, SNMPv2c and SNMPv3 include authorization
 (encryption not yet supported!)

Used RFC: RFC-1157, RFC-1901, RFC-3412, RFC-3414, RFC-3416
}

{$IFDEF FPC}
  {$MODE DELPHI}
{$ENDIF}
{$Q-}
{$H+}

unit snmpsend;

interface

uses
  Classes, SysUtils,
  blcksock, synautil, asn1util, synacode;

const
  cSnmpProtocol = '161';
  cSnmpTrapProtocol = '162';

  SNMP_V1 = 0;
  SNMP_V2C = 1;
  SNMP_V3 = 3;

  //PDU type
  PDUGetRequest = $A0;
  PDUGetNextRequest = $A1;
  PDUGetResponse = $A2;
  PDUSetRequest = $A3;
  PDUTrap = $A4; //Obsolete
  //for SNMPv2
  PDUGetBulkRequest = $A5;
  PDUInformRequest = $A6;
  PDUTrapV2 = $A7;
  PDUReport = $A8;

  //errors
  ENoError = 0;
  ETooBig = 1;
  ENoSuchName = 2;
  EBadValue = 3;
  EReadOnly = 4;
  EGenErr = 5;
  //errors SNMPv2
  ENoAccess = 6;
  EWrongType = 7;
  EWrongLength = 8;
  EWrongEncoding = 9;
  EWrongValue = 10;
  ENoCreation = 11;
  EInconsistentValue = 12;
  EResourceUnavailable = 13;
  ECommitFailed = 14;
  EUndoFailed = 15;
  EAuthorizationError = 16;
  ENotWritable = 17;
  EInconsistentName = 18;

type

  {:@abstract(Possible values for SNMPv3 flags.)
   This flags specify level of authorization and encryption.}
  TV3Flags = (
    NoAuthNoPriv,
    AuthNoPriv,
    AuthPriv);

  {:@abstract(Type of SNMPv3 authorization)}
  TV3Auth = (
    AuthMD5,
    AuthSHA1);

  {:@abstract(Data object with one record of MIB OID and corresponding values.)}
  TSNMPMib = class(TObject)
  protected
    FOID: AnsiString;
    FValue: AnsiString;
    FValueType: Integer;
  published
    {:OID number in string format.}
    property OID: AnsiString read FOID write FOID;

    {:Value of OID object in string format.}
    property Value: AnsiString read FValue write FValue;

    {:Define type of Value. Supported values are defined in @link(asn1util).
     For queries use ASN1_NULL, becouse you don't know type in response!}
    property ValueType: Integer read FValueType write FValueType;
  end;

  {:@abstract(It holding all information for SNMPv3 agent synchronization)
   Used internally.}
  TV3Sync = record
    EngineID: AnsiString;
    EngineBoots: integer;
    EngineTime: integer;
    EngineStamp: Cardinal;
  end;

  {:@abstract(Data object abstracts SNMP data packet)}
  TSNMPRec = class(TObject)
  protected
    FVersion: Integer;
    FPDUType: Integer;
    FID: Integer;
    FErrorStatus: Integer;
    FErrorIndex: Integer;
    FCommunity: AnsiString;
    FSNMPMibList: TList;
    FMaxSize: Integer;
    FFlags: TV3Flags;
    FFlagReportable: Boolean;
    FContextEngineID: AnsiString;
    FContextName: AnsiString;
    FAuthMode: TV3Auth;
    FAuthEngineID: AnsiString;
    FAuthEngineBoots: integer;
    FAuthEngineTime: integer;
    FAuthEngineTimeStamp: cardinal;
    FUserName: AnsiString;
    FPassword: AnsiString;
    FAuthKey: AnsiString;
    FPrivKey: AnsiString;
    FOldTrapEnterprise: AnsiString;
    FOldTrapHost: AnsiString;
    FOldTrapGen: Integer;
    FOldTrapSpec: Integer;
    FOldTrapTimeTicks: Integer;
    function Pass2Key(const Value: AnsiString): AnsiString;
  public
    constructor Create;
    destructor Destroy; override;

    {:Decode SNMP packet in buffer to object properties.}
    function DecodeBuf(const Buffer: AnsiString): Boolean;

    {:Encode obeject properties to SNMP packet.}
    function EncodeBuf: AnsiString;

    {:Clears all object properties to default values.}
    procedure Clear;

    {:Add entry to @link(SNMPMibList). For queries use value as empty string,
     and ValueType as ASN1_NULL.}
    procedure MIBAdd(const MIB, Value: AnsiString; ValueType: Integer);

    {:Delete entry from @link(SNMPMibList).}
    procedure MIBDelete(Index: Integer);

    {:Search @link(SNMPMibList) list for MIB and return correspond value.}
    function MIBGet(const MIB: AnsiString): AnsiString;

    {:return number of entries in MIB array.}
    function MIBCount: integer;

    {:Return MIB information from given row of MIB array.}
    function MIBByIndex(Index: Integer): TSNMPMib;

    {:List of @link(TSNMPMib) objects.}
    property SNMPMibList: TList read FSNMPMibList;
  published
    {:Version of SNMP packet. Default value is 0 (SNMP ver. 1). You can use
     value 1 for SNMPv2c or value 3 for SNMPv3.}
    property Version: Integer read FVersion write FVersion;

    {:Community string for autorize access to SNMP server. (Case sensitive!)
     Community string is not used in SNMPv3! Use @link(Username) and
     @link(password) instead!}
    property Community: AnsiString read FCommunity write FCommunity;

    {:Define type of SNMP operation.}
    property PDUType: Integer read FPDUType write FPDUType;

    {:Contains ID number. Not need to use.}
    property ID: Integer read FID write FID;

    {:When packet is reply, contains error code. Supported values are defined by
     E* constants.}
    property ErrorStatus: Integer read FErrorStatus write FErrorStatus;

    {:Point to error position in reply packet. Not usefull for users. It only
     good for debugging!}
    property ErrorIndex: Integer read FErrorIndex write FErrorIndex;

    {:special value for GetBulkRequest of SNMPv2 and v3.}
    property NonRepeaters: Integer read FErrorStatus write FErrorStatus;

    {:special value for GetBulkRequest of SNMPv2 and v3.}
    property MaxRepetitions: Integer read FErrorIndex write FErrorIndex;

    {:Maximum message size in bytes for SNMPv3. For sending is default 1472 bytes.}
    property MaxSize: Integer read FMaxSize write FMaxSize;

    {:Specify if message is authorised or encrypted. Used only in SNMPv3, and
     encryption is not yet supported!}
    property Flags: TV3Flags read FFlags write FFlags;

    {:For SNMPv3.... If is @true, SNMP agent must send reply (at least with some
     error).}
    property FlagReportable: Boolean read FFlagReportable write FFlagReportable;

    {:For SNMPv3. If not specified, is used value from @link(AuthEngineID)}
    property ContextEngineID: AnsiString read FContextEngineID write FContextEngineID;

    {:For SNMPv3.}
    property ContextName: AnsiString read FContextName write FContextName;

    {:For SNMPv3. Specify Authorization mode. (specify used hash for
     authorization)}
    property AuthMode: TV3Auth read FAuthMode write FAuthMode;

    {:value used by SNMPv3 authorisation for synchronization with SNMP agent.}
    property AuthEngineID: AnsiString read FAuthEngineID write FAuthEngineID;

    {:value used by SNMPv3 authorisation for synchronization with SNMP agent.}
    property AuthEngineBoots: Integer read FAuthEngineBoots write FAuthEngineBoots;

    {:value used by SNMPv3 authorisation for synchronization with SNMP agent.}
    property AuthEngineTime: Integer read FAuthEngineTime write FAuthEngineTime;

    {:value used by SNMPv3 authorisation for synchronization with SNMP agent.}
    property AuthEngineTimeStamp: Cardinal read FAuthEngineTimeStamp Write FAuthEngineTimeStamp;

    {:SNMPv3 authorization username}
    property UserName: AnsiString read FUserName write FUserName;

    {:SNMPv3 authorization password}
    property Password: AnsiString read FPassword write FPassword;

    {:For SNMPv3. Computed Athorization key from @link(password).}
    property AuthKey: AnsiString read FAuthKey write FAuthKey;

    {:For SNMPv3. Encryption key for message encryption. Not yet used!}
    property PrivKey: AnsiString read FPrivKey write FPrivKey;

    {:MIB value to identify the object that sent the TRAPv1.}
    property OldTrapEnterprise: AnsiString read FOldTrapEnterprise write FOldTrapEnterprise;

    {:Address of TRAPv1 sender (IP address).}
    property OldTrapHost: AnsiString read FOldTrapHost write FOldTrapHost;

    {:Generic TRAPv1 identification.}
    property OldTrapGen: Integer read FOldTrapGen write FOldTrapGen;

    {:Specific TRAPv1 identification.}
    property OldTrapSpec: Integer read FOldTrapSpec write FOldTrapSpec;

    {:Number of 1/100th of seconds since last reboot or power up. (for TRAPv1)}
    property OldTrapTimeTicks: Integer read FOldTrapTimeTicks write FOldTrapTimeTicks;
  end;

  {:@abstract(Implementation of SNMP protocol.)

   Note: Are you missing properties for specify server address and port? Look to
   parent @link(TSynaClient) too!}
  TSNMPSend = class(TSynaClient)
  protected
    FSock: TUDPBlockSocket;
    FBuffer: AnsiString;
    FHostIP: AnsiString;
    FQuery: TSNMPRec;
    FReply: TSNMPRec;
    function InternalSendSnmp(const Value: TSNMPRec): Boolean;
    function InternalRecvSnmp(const Value: TSNMPRec): Boolean;
    function InternalSendRequest(const QValue, RValue: TSNMPRec): Boolean;
    function GetV3EngineID: AnsiString;
    function GetV3Sync: TV3Sync;
  public
    constructor Create;
    destructor Destroy; override;

    {:Connects to a Host and send there query. If in timeout SNMP server send
     back query, result is @true. If is used SNMPv3, then it synchronize self
     with SNMPv3 agent first. (It is needed for SNMPv3 auhorization!)}
    function SendRequest: Boolean;

    {:Send SNMP packet only, but not waits for reply. Good for sending traps.}
    function SendTrap: Boolean;

    {:Receive SNMP packet only. Good for receiving traps.}
    function RecvTrap: Boolean;

    {:Mapped to @link(SendRequest) internally. This function is only for
     backward compatibility.}
    function DoIt: Boolean;
  published
    {:contains raw binary form of SNMP packet. Good for debugging.}
    property Buffer: AnsiString read FBuffer write FBuffer;

    {:After SNMP operation hold IP address of remote side.}
    property HostIP: AnsiString read FHostIP;

    {:Data object contains SNMP query.}
    property Query: TSNMPRec read FQuery;

    {:Data object contains SNMP reply.}
    property Reply: TSNMPRec read FReply;

    {:Socket object used for TCP/IP operation. Good for seting OnStatus hook, etc.}
    property Sock: TUDPBlockSocket read FSock;
  end;

{:A very useful function and example of its use would be found in the TSNMPSend
 object. It implements basic GET method of the SNMP protocol. The MIB value is
 located in the "OID" variable, and is sent to the requested "SNMPHost" with
 the proper "Community" access identifier. Upon a successful retrieval, "Value"
 will contain the information requested. If the SNMP operation is successful,
 the result returns @true.}
function SNMPGet(const OID, Community, SNMPHost: AnsiString; var Value: AnsiString): Boolean;

{:This is useful function and example of use TSNMPSend object. It implements

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -