SNMP to go to Raiders

xiaoxiao2021-03-06  57

DKProjects> CSRSNMP> DOC> Learn> Authorship> SNMPBEGINGCODESNMP Beging Coding 1. Introduction. Preparation

2.1 Install SNMP Agent 2.2 Examples 2.3 Run

SNMP to go to Raiders

-------------------------------------------------- ------------------------------ version: 1.0 author: Soundboy date: 2004-9-14 NOTE: This article describes how to use the most Simple configuration (a single PC), execute a simplest SNMP program -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ------------------------------------------------

I. Introduction needs to use SNMP development, so I immediately use various resources, libraries, books, and Internet to enjoy all relevant information. SNMP is an English abbreviation of simple network management protocol, which can be used to do network management. Although this information is not as flood like C and other technologies (for the publication of today C fields, I am willing to use floods, I don't want to use rich, run, ^ _ ^), but it is not a lack of good. Search SNMP on 9CBS and Google. It is a lot of pile. However, communication is (maybe I am looking for not enough), such as SNMP history, what is SNMP, and the SNMP is more favorable with other protocols. There is no doubt that such an article has never heard of SNMP like I have never heard of Snmp. But joy is short, when you understand the concept of Hello World, you want to see a program like Hello World. I can't find a Demo that can be easily run.

So this article no longer introduces the concept of SNMP, but step on how to implement "Hello World" of a SNMP program. About Concept "SNMP Network Management" William Stallings. There is a detailed introduction in China's Power Publishing book. But I can't stand it is that there is almost no code of the whole book. Maybe this book itself is not to see the programmer, and the translation of the book also gives people like a large stall in the roadside.

II. Preparation I use Win2k Professional SP4 Chinese version, other platforms I really have no time trial, but it should be similar.

2.1 Installing SNMP Agent first ensures that there is SNMP service on your machine. Place installed In the Network and Dial Links Form, you can get the "Online Neighbor -> Properties" by right-click on the desktop.

Select the Advanced-> Optional Network Component menu in the Network and Dial-up links, the following dialog box appears:

In this dialog, you want to ensure that the Administration and Monitoring Tools is selected, the related components of SNMP are in this option, and this option is not installed by default. If your machine is still not installed, let's choose.

2.2 Examples Example I write an example of an example that it doesn't seem to be, if you can write a SNMP program yourself, then this article should not look. We use the examples on the MSDN directly. There is such an example on the MSDN of VS6 in ... / Samples / VC98 / SDK / NETDS / SNMP / SNMPUTIL. Interesting is what conditions do not need to be running in this example of the ReadMe. The reason for understanding is that this program is not used on the local PC, but a remote network device such as a router.

Although I believe that many places can find this program, but I still put its code here, and I seem to have a "share". II to give someone who has no MSDN on a few machines. Three came this code, I made a little modification. When I print a character description of the cause of the error, the original example gives an integer code. What is the reason why people can't be visually know. This example is a Console program, no form, dialog box. And it is also very convenient to post it. There is also a Makefile file, which is not listed here.

The following is a snmputil.c file:

/ * build version: 0001 // increment this if a change Has Global Effects

Copyright (c) 1991-1995 Microsoft Corporation Module Name: snmputil.c Abstract:. Sample SNMP Management API usage for Windows NT This file is an example of how to code management applications using the SNMP Management API for Windows NT It is similar in. operation to the other commonly available SNMP command line utilities Extensive comments have been included to describe its structure and operation See also "Microsoft Windows / NT SNMP Programmer's Reference" Created: 28-Jun-1991 Revision History: -... * /

Static char * vcsid = "@ (#) $ logfile: n: /agent/mgmtapi/vcs/snmputil.c_v $ Revision: 1.5 $

// General notes: // Microsoft's SNMP Management API for Windows NT is implemented as a DLL // that is linked with the developer's code These APIs (examples follow in // this file) allow the developer's code to generate SNMP queries and receive. // SNMP Traps. A Simple Mib Compiler and Related Apis Are Also Available To // Allow Conversions Between Object Identifiers and Object Descriptors.

// Necessary includes.

#include

#include #include #include #include #include

// Constants Used in this Example.

#define get 1 # Define getnext 2 # define wall 3 # Define Trap 4

#define Timeout 6000 / * MilliseConds * / # Define Retries 3

// main program.

INT _CRTAPI1 main (IN int argumentCount, IN char * argumentVector []) {INT operation; LPSTR agent; LPSTR community; RFC1157VarBindList variableBindings; LPSNMP_MGR_SESSION session; INT timeout = TIMEOUT; INT retries = RETRIES; BYTE requestType; AsnInteger errorStatus; AsnInteger errorIndex; char * chkPtr = NULL; // Parse command line arguments to determine requested operation // Verify number of arguments ... if (argumentCount <5 && argumentCount = 2!) {printf ( "Error:. Incorrect number of arguments specified./ N "); Printf (" / Nusage: snmputil [get | getnext | walk] agent community OID [OID ...] / N "); Printf (" snmputil trap / n "); return 1;} // Get / Verify Operation ... argumentVector ; argumentcount -; if (! strcmp (* arg UtionVector, "get")) Operation = get; else if (! strcmp (* argumentVector, "getnext")) Operation = getNext; else if (! strcmp (* argumentVector, "walk"))))))))))))). ! strcmp (* argumentvector, "trap")) Operation = trap; Else {Printf ("Error: Invalid Operation, '% s', specified./n", * argumentVector); Return 1;} if (Operation! = TRAP ) {IF (argumentcount <4) {printf ("error: incorrect number of arguments specified./N"); Printf ("

/ NUSAGE: SNMPUTIL [GET | GetNext | Walk] Agent Community OID [OID ...] / N "); Printf (" SNMPUTIL TRAP / N "); Return 1;} // Get Agent Address ... argumentVector ; argumentcount -; agent = (LPSTR) SNMP_malloc (strlen (* argumentVector) 1); strcpy (agent, * argumentVector); // Get agent community ... argumentVector ; argumentCount--; community = (LPSTR) SNMP_malloc (strlen ( * argumentVector) 1); strcpy (community, * argumentVector); // Get oid's ... variableBindings.list = NULL; variableBindings.len = 0; while (- argumentCount) {AsnObjectIdentifier reqObject; argumentVector ; // Convert the String representation to an internal representation. if (! snmpmgrstooid (* argumentvector, & reqbject) {Printf ("Error: Inva lid oid,% s, specified./n ", * argumentVector); return 1;} else {// Since sucessfull, add to the variable bindings list variableBindings.len ;. if ((variableBindings.list = (RFC1157VarBind *) SNMP_realloc (Variablebindings.list, sizeof (rfc1157varbind) * variablebindings.len) == null) {Printf ("error: error allocating OID,% s. / N", * argumentVector; Return 1;

} VariableBindings.list [variableBindings.len - 1] .name = reqObject;! // NOTE structure copy variableBindings.list [variableBindings.len - 1] .value.asnType = ASN_NULL;}} // end while () // Make Sure Only One Variable Binding Was Specified IF Operation // IS Walk. if (Operation == Walk && VariableBindings.len! = 1) {Printf ("Error: Multiple Oids Specified for Walk./N"); Return 1;} / / Establish a SNMP session to communicate with the remote agent. The // community, communications timeout, and communications retry count // for the session are also required. if ((session = SnmpMgrOpen (agent, community, timeout, retries)) = = NULL) {Printf ("ERROR ON SNMPMGROPEN% D / N", getLastError ()); return 1;}} // end if (TRAP) // Determine and perform the requested operation. if (operation == GET || operation == GETNEXT) {// Get and GetNext are relatively simple operations to perform. // Simply initiate the request and process the result and / or // possible error conditions if (operation == GET) requestType = ASN_RFC1157_GETREQUEST;. else requestType = ASN_RFC1157_GETNEXTREQUEST;.! // Request that the API carry out the desired operation if (SnmpMgrRequest (session, requestType, & variableBindings, &

ErrorStatus, & Errorindex) {// The API IS INDICATING An Error. Printf ("Error On SNMPMGRRRRRRRRRRRROR D / N", getLastError ());} else {// The API SuCceeded, Errors May Be Indicated from The Remote // . agent switch (errorStatus) {case SNMP_ERRORSTATUS_TOOBIG: {printf ( "SNMP_ERRORSTATUS_TOOBIG"); break;} case SNMP_ERRORSTATUS_NOSUCHNAME: {printf ( "SNMP_ERRORSTATUS_NOSUCHNAME"); break;} case SNMP_ERRORSTATUS_BADVALUE: {printf ( "SNMP_ERRORSTATUS_BADVALUE"); break;} default : Break;} if (ErrorStatus> 0) {Printf ("Error: Errorstatus =% D, ErrorIndex =% D / N", errorStatus, errorIndex);} else {// Display the resulting variable bindings UINT i;. char * string = NULL; for (i = 0; i

} // Test for General Error Conditions or Sucesss. If ("Error: ErrorStatus =% D, ErrorIndex =% D / N", Errorstatus, Errorindex; Break;} else {// Display results Variable binding for this ity; snmpmgroidtostr (& variablebindings.list [0] .name, & string); printf ("variable =% s / n", string; if (string) snmp_free (string); Printf ("Value ="); SNMPUTILPRINTASNANY (& variablebindings.list [0] .value); Printf ("/ n");}} // end if () // prepare f . Or the next iteration Make sure returned oid is // preserved and the returned value is freed SnmpUtilOidCpy (& tempOid, & variableBindings.list [0] .name);. SnmpUtilVarBindFree (& variableBindings.list [0]); SnmpUtilOidCpy (& variableBindings.list [ 0] .name, & tempOid); variableBindings.list [0] .value.asnType = ASN_NULL; SnmpUtilOidFree (& tempOid);} // end while () // Free the variable bindings that have been allocated SnmpUtilVarBindListFree (& variableBindings).;

SnmpUtilOidFree (& root);} else if (operation == TRAP) {// Trap handling can be done two different ways: event driven or // polled The following code illustrates the steps to use event // driven trap reception in a management. . application HANDLE hNewTraps = NULL; if {printf ( "error on SnmpMgrTrapListen% d / n", GetLastError ());} else {printf ((SnmpMgrTrapListen (& hNewTraps)!) "snmputil: listening for traps ... / n" );} While (1) {DWORD DWRESULT; IF ((DWRESULT = WaitFforSingleObject (HNEWTRAPS, 0xFFFFFFF) == 0xffffff) {Printf ("Error On WaitForsingleObject% D / N", getLastError ());} else if (! ResetEvent (HNEWTRAPS)) {Printf ("Error On ResetEvent% D / N", getLastEverRor ()); } Else {AsnObjectIdentifier enterprise; AsnNetworkAddress IPAddress; AsnInteger genericTrap; AsnInteger specificTrap; AsnTimeticks timeStamp; RFC1157VarBindList variableBindings; UINT i; char * string = NULL; while (SnmpMgrGetTrap (& enterprise, & IPAddress, & genericTrap, & specificTrap, & timeStamp, & variableBindings)) {printf ( "SNMPUTIL: TRAP generic =

% D Specific =% D / N ", GenericTrap, SpecificTrap); if (ipaddress.Length == 4) {Printf (" from ->% d.% d.% d.% d / n ", (int) ipaddress .stream [0], (int) ipaddress.stream [1], (int) ipaddress.stream [2], (int) ipaddress.stream [3]);} if (ipaddress.dynamic) {SNMP_Free (ipaddress.stream );} For (i = 0; i

# Nmake macros for building windows 32-bit appstargetos = Winnt

Include

! IF "$ (cpu) ==" i386 "cflags = $ (cflags) -d_crtapi1 = _CDECL -D_CRTAPI2 = _CDECL! ELSECFLAGS = $ (cflags) -d_crtapi1 = -d_crtapi2 =! ENDIF

All: SNMPUTIL.EXE

SNMPUTIL.OBJ: SNMPUTIL.C $ (CC) $ (CFLAGS) $ (CDEBUG) SNMPUTIL.C

SNMPUTIL.EXE: SNMPUTIL.OBJ $ (LINK) $ (Conflags) - --Out: snmputil.exe snmputil.obj $ (conlibsdll) / advapi32.lib SNMPAPI.LIB mgmtapi.lib If there is a link error, then 80% It is because two library files to the MGMTAPI.LIB SNMPAPI.lib are added to the link option.

Run this program to generate SNMPUTIL.EXE

2.3 Run Enter SNMPUTIL GET in command mode Your IP address or user name public .1.3.6.1.2.1.1.1.0

Does it see your machine-related information. If you are the other machine on the network, if you have SNMP installed, you can also see his information. As for why what is used, please continue to learn again.

转载请注明原文地址:https://www.9cbs.com/read-117278.html

New Post(0)