snmpwalk.java.txt
上传用户:aonuowh
上传日期:2021-05-23
资源大小:35390k
文件大小:9k
源码类别:

SNMP编程

开发平台:

C/C++

  1. /* $Id: snmpwalk.src,v 1.6 2002/09/09 05:36:52 parasuraman Exp $ */
  2. /*
  3.  * @(#)snmpwalk.java
  4.  * Copyright (c) 1996-2003 AdventNet, Inc. All Rights Reserved.
  5.  * Please read the associated COPYRIGHTS file for more details.
  6.  */
  7. /**
  8.  * This is an example program to explain how to write an application to do
  9.  * the basic SNMP operation WALK using com.adventnet.snmp.snmp2 package of
  10.  * AdventNetSNMP2 api.
  11.  * The user could run this application by giving any one of the following usage.
  12.  *  
  13.  * java snmpwalk [options] hostname oid
  14.  *
  15.  * v1 request: 
  16.  * java snmpwalk snmpwalk [-d] [-c community] [-p port] [-t timeout] [-r retries] host OID
  17.  * e.g. 
  18.  * java snmpwalk -p 161 -c public adventnet .1.3.6.1 
  19.  *<img SRC="images/v2candv3only.jpg" ALT="v2c and v3 only">
  20.  * v2c request:  
  21.  * java snmpwalk [-d] [-v version(v1,v2)] [-c community] [-p port] [-t timeout] [-r retries] host OID
  22.  * e.g. 
  23.  * java snmpwalk -v v2 -p 161 -c public -m rfc1213-mib adventnet .1.3.6.1
  24.  *<img SRC="images/v3only.jpg" ALT="v3 only"> 
  25.  * v3 request:
  26.  * java snmpwalk [-d] [-v version(v1,v2,v3)] [-c community] [-p port] [-r retries] [-t timeout] [-u user] [-a auth_protocol] [-w auth_password] [-s priv_password] [-i context_id] host OID
  27.  * e.g.
  28.  * java snmpwalk -v v3 -u initial2 -w initial2Pass -a MD5 10.3.2.120 .1.3
  29.  * 
  30.  * If the oid is not starting with a dot (.) it will be prefixed by .1.3.6.1.2.1 .
  31.  * So the entire OID of 1.1.0 will become .1.3.6.1.2.1.1.1.0 . You can also
  32.  * give the entire OID .
  33.  * 
  34.  * Options:
  35.  * [-d]                - Debug output. By default off.
  36.  * [-c] <community>    - community String. By default "public".
  37.  * [-p] <port>         - remote port no. By default 161.
  38.  * [-t] <Timeout>      - Timeout. By default 5000ms.
  39.  * [-r] <Retries>      - Retries. By default 0.      
  40.  *<img SRC="images/v3only.jpg" ALT="v3 only"> [-v] <version>      - version(v1 / v2 / v3). By default v1.
  41.  * [-u] <username>     - The v3 principal/userName
  42.  * [-a] <autProtocol>  - The authProtocol(MD5/SHA). Mandatory if authPassword is specified
  43.  * [-w] <authPassword> - The authentication password.
  44.  * [-s] <privPassword> - The privacy protocol password. Must be accompanied with auth password and authProtocol fields.
  45.  * [-n] <contextName>  - The context to be used for the v3 pdu.
  46.  * [-i] <contextID>    - The context to be used for the v3 pdu.
  47.  * <host> Mandatory    - The RemoteHost (agent).Format (string without double qoutes/IpAddress).
  48.  * <OID>  Mandatory    - Give multiple no. of Object Identifiers.
  49.  */
  50. import java.lang.*;
  51. import java.util.*;
  52. import java.net.*;
  53. import com.adventnet.snmp.snmp2.*;
  54. import com.adventnet.snmp.snmp2.usm.*;
  55. public class snmpwalk
  56. {
  57. public static void main(String args[])
  58. {
  59.  
  60.         // Take care of getting options
  61. String usage =
  62. "nsnmpwalk [-d] [-v version(v1,v2,v3)] n" +
  63. "[-c community] [-p port] [-r retries] n" +
  64. "[-t timeout] [-u user] [-a auth_protocol] n" +
  65. "[-w auth_password] [-s priv_password] n" +
  66. "[-n contextName] [-i contextID] n" +
  67. "[-DB_driver database_driver]n" +
  68. "[-DB_url database_url]n" +
  69. "[-DB_username database_username]n" +
  70. "[-DB_password database_password]n" +
  71. "host OIDn";
  72. String options[] =
  73. {
  74. "-d", "-c",  "-wc", "-p", "-r", "-t", "-m",
  75. "-v", "-u", "-a", "-w", "-s", "-n", "-i",
  76. "-DB_driver", "-DB_url", "-DB_username", "-DB_password"
  77. };
  78.         String values[] =
  79. {
  80. "None", null, null, null, null, null, "None",
  81. null, null, null, null, null, null, null,
  82. null, null, null, null
  83. };
  84. ParseOptions opt = new ParseOptions(args,options,values, usage);
  85. if (opt.remArgs.length!=2)
  86. {
  87. opt.usage_error();
  88. }
  89.         
  90. // Start SNMP API
  91. SnmpAPI api;
  92. api = new SnmpAPI();
  93. if (values[0].equals("Set"))
  94. {
  95. api.setDebug( true );
  96. }
  97. // Open session
  98. SnmpSession session = new SnmpSession(api);
  99. // set remote Host 
  100. session.setPeername( opt.remArgs[0] );
  101. //set the values
  102. SetValues setVal = new SetValues(session, values);
  103. if(setVal.usage_error)
  104. {
  105. opt.usage_error(); 
  106. }
  107. String driver = values[14];
  108. String url = values[15];
  109. String username = values[16];
  110. String password = values[17];
  111. if(driver != null || url != null ||
  112. username != null || password != null)
  113. {
  114. if(session.getVersion() != 3)
  115. {
  116. System.out.println(
  117. "Database option can be used only for SNMPv3.");
  118. System.exit(1);
  119. }
  120. if(driver == null)
  121. {
  122. System.out.println(
  123. "The Database driver name should be given.");
  124. System.exit(1);
  125. }
  126. if(url == null)
  127. {
  128. System.out.println("The Database URL should be given.");
  129. System.exit(1);
  130. }
  131. try
  132. {
  133. api.setV3DatabaseFlag(true);
  134. api.initJdbcParams(driver, url, username, password);
  135. }
  136. catch(Exception exp)
  137. {
  138. System.out.println("Unable to Establish Database Connection.");
  139. System.out.println("Please check the driverName and url.");
  140. System.exit(1);
  141. }
  142. }
  143. // Build GETNEXT request PDU
  144. SnmpPDU pdu = new SnmpPDU();
  145. pdu.setCommand( api.GETNEXT_REQ_MSG );
  146. // need to save the root OID to walk sub-tree
  147. SnmpOID oid = new SnmpOID(opt.remArgs[1]);
  148. int rootoid[] = (int[]) oid.toValue();  
  149. if (rootoid == null) //if don't have a valid OID for first, exit
  150. {
  151. System.err.println("Invalid OID argument: " + opt.remArgs[1]);
  152. System.exit(1);
  153. }
  154. else
  155. {
  156. pdu.addNull(oid);
  157. }
  158. try
  159. {
  160. session.open();
  161. }
  162. catch (SnmpException e)
  163. {
  164. System.err.println("Error in open session "+e.getMessage());
  165. System.exit(1);
  166. }
  167.         
  168.         if(session.getVersion()==SnmpAPI.SNMP_VERSION_3)
  169. {
  170. System.out.println("UserName = " + setVal.userName);
  171. pdu.setUserName(setVal.userName.getBytes());
  172.             USMUtils.init_v3_params(
  173. setVal.userName,
  174. setVal.authProtocol,
  175. setVal.authPassword,
  176. setVal.privPassword,
  177. session.getPeername(),
  178. session.getRemotePort(),
  179. session);
  180.             pdu.setContextName(setVal.contextName.getBytes());
  181.             pdu.setContextID(setVal.contextID.getBytes());
  182.         }
  183. // loop for each PDU in the walk
  184. while (true) // until received OID isn't in sub-tree
  185. {
  186. try
  187. {
  188. // Send PDU and receive response PDU
  189. pdu = session.syncSend(pdu);
  190. }
  191. catch (SnmpException e)
  192. {
  193. System.err.println("Sending PDU"+e.getMessage());
  194. System.exit(1);
  195. }
  196. if (pdu == null)
  197. {
  198. // timeout
  199. System.out.println("Request timed out to: " + opt.remArgs[0] );
  200. System.exit(1);
  201. }
  202. // stop if outside sub-tree
  203. if (!isInSubTree(rootoid,pdu))
  204. {
  205. System.out.println("Not in sub tree.");
  206. break; 
  207. }
  208. int version = pdu.getVersion();
  209. if(version == SnmpAPI.SNMP_VERSION_1)
  210. {
  211. // check for error 
  212. if (pdu.getErrstat() != 0)
  213. {
  214. System.out.println("Error Indication in response: " +
  215. SnmpException.exceptionString((byte)pdu.getErrstat()) + 
  216. "nErrindex: " + pdu.getErrindex()); 
  217. System.exit(1);
  218. }
  219. // print response pdu variable-bindings                    
  220. System.out.println(pdu.printVarBinds());
  221.             }
  222. else if((version == SnmpAPI.SNMP_VERSION_2C) ||
  223. (version == SnmpAPI.SNMP_VERSION_3))
  224. {
  225. Enumeration e = pdu.getVariableBindings().elements();
  226. while(e.hasMoreElements())
  227. {
  228. int error = 0;
  229. SnmpVarBind varbind = (SnmpVarBind)e.nextElement();
  230. // check for error
  231. if ( (error = varbind.getErrindex()) != 0)
  232. {
  233. System.out.println("Error Indication in response: " +
  234. SnmpException.exceptionString((byte)error));
  235. System.exit(1);
  236. }
  237. // print response pdu variable-bindings
  238. System.out.println(pdu.printVarBinds());
  239. }
  240.             }
  241. else
  242. {
  243. System.out.println("Invalid Version Number");
  244. }
  245. // set GETNEXT_REQ_MSG to do walk
  246. // Don't forget to set request id to 0 otherwise next request will fail
  247. pdu.setReqid(0);
  248. SnmpOID first_oid = pdu.getObjectID(0);
  249. pdu = new SnmpPDU();
  250. pdu.setCommand( api.GETNEXT_REQ_MSG );
  251. pdu.setUserName(setVal.userName.getBytes());
  252. pdu.setContextName(setVal.contextName.getBytes());
  253. pdu.setContextID(setVal.contextID.getBytes());
  254. pdu.addNull(first_oid);
  255. } // end of while true
  256.         
  257. // Print the GroupCounters
  258. String[] localAddr = session.getLocalAddresses();
  259. int localPort = session.getLocalPort();
  260. SnmpGroup group = api.getSnmpGroup(localAddr[localAddr.length - 1],localPort);
  261. if(group != null)
  262. {
  263. System.out.println("The SnmpGroup Counter values :");
  264. System.out.println("snmpInPkts = " + group.getSnmpInPkts());
  265. System.out.println("snmpOutPkts = " + group.getSnmpOutPkts());
  266. System.out.println("snmpInGetResponses = " + group.getSnmpInGetResponses());
  267. System.out.println("snmpOutGetRequests = " + group.getSnmpOutGetRequests());
  268. System.out.println("snmpOutGetNexts = " + group.getSnmpOutGetNexts());
  269. }
  270. // close session
  271. session.close();
  272. // stop api thread
  273. api.close();
  274. System.exit(0);
  275. }
  276.     /** check if first varbind oid has rootoid as an ancestor in MIB tree */
  277. static boolean isInSubTree(int[] rootoid, SnmpPDU pdu)
  278. {
  279. SnmpOID objID = (SnmpOID) pdu.getObjectID(0);
  280. if (objID == null)
  281. {
  282. return false;
  283. }
  284. int oid[] = (int[]) objID.toValue();
  285. if (oid == null)
  286. {
  287. return false;        
  288. }
  289. if (oid.length < rootoid.length)
  290. {
  291. return false;
  292. }
  293. for (int i=0;i<rootoid.length;i++)
  294. {
  295. if (oid[i] != rootoid[i])
  296. {
  297. return false;
  298. }
  299. }
  300. return true;
  301. }
  302. }