linux 下net-snmp简单例子

原文地址:http://blog.csdn.net/fantasylf/article/details/5692770

这里我们讨论怎么写个简单的应用。它只是简单的接受来自远程主机的信息。下面是源代码和makefile

[cpp]  view plain  copy
  1. #include <net-snmp/net-snmp-config.h>  
  2. #include <net-snmp/net-snmp-includes.h>  
  3. #include <string.h>  
  4. /* change the word "define" to "undef" to try the (insecure) SNMPv1 version */  
  5. #define DEMO_USE_SNMP_VERSION_3  
  6. #ifdef DEMO_USE_SNMP_VERSION_3  
  7. const char *our_v3_passphrase = "The Net-SNMP Demo Password";  
  8. #endif  
  9. int main(int argc, char ** argv)  
  10. {  
  11.     netsnmp_session session, *ss;  
  12.     netsnmp_pdu *pdu;  
  13.     netsnmp_pdu *response;  
  14.     oid anOID[MAX_OID_LEN];  
  15.     size_t anOID_len;  
  16.     netsnmp_variable_list *vars;  
  17.     int status;  
  18.     int count=1;  
  19.     /* 
  20.      * Initialize the SNMP library 
  21.      */  
  22.     init_snmp("snmpdemoapp");  
  23.     /* 
  24.      * Initialize a "session" that defines who we're going to talk to 
  25.      */  
  26.     snmp_sess_init( &session );                   /* set up defaults */  
  27.     session.peername = strdup("test.net-snmp.org");  
  28.     /* set up the authentication parameters for talking to the server */  
  29. #ifdef DEMO_USE_SNMP_VERSION_3  
  30.     /* Use SNMPv3 to talk to the experimental server */  
  31.     /* set the SNMP version number */  
  32.     session.version=SNMP_VERSION_3;  
  33.           
  34.     /* set the SNMPv3 user name */  
  35.     session.securityName = strdup("MD5User");  
  36.     session.securityNameLen = strlen(session.securityName);  
  37.     /* set the security level to authenticated, but not encrypted */  
  38.     session.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;  
  39.     /* set the authentication method to MD5 */  
  40.     session.securityAuthProto = usmHMACMD5AuthProtocol;  
  41.     session.securityAuthProtoLen = sizeof(usmHMACMD5AuthProtocol)/sizeof(oid);  
  42.     session.securityAuthKeyLen = USM_AUTH_KU_LEN;  
  43.     /* set the authentication key to a MD5 hashed version of our 
  44.        passphrase "The Net-SNMP Demo Password" (which must be at least 8 
  45.        characters long) */  
  46.     if (generate_Ku(session.securityAuthProto,  
  47.                     session.securityAuthProtoLen,  
  48.                     (u_char *) our_v3_passphrase, strlen(our_v3_passphrase),  
  49.                     session.securityAuthKey,  
  50.                     &session.securityAuthKeyLen) != SNMPERR_SUCCESS) {  
  51.         snmp_perror(argv[0]);  
  52.         snmp_log(LOG_ERR,  
  53.                  "Error generating Ku from authentication pass phrase. /n");  
  54.         exit(1);  
  55.     }  
  56.       
  57. #else /* we'll use the insecure (but simplier) SNMPv1 */  
  58.     /* set the SNMP version number */  
  59.     session.version = SNMP_VERSION_1;  
  60.     /* set the SNMPv1 community name used for authentication */  
  61.     session.community = "demopublic";  
  62.     session.community_len = strlen(session.community);  
  63. #endif /* SNMPv1 */  
  64.     /* 
  65.      * Open the session 
  66.      */  
  67.     SOCK_STARTUP;  
  68.     ss = snmp_open(&session);                     /* establish the session */  
  69.     if (!ss) {  
  70.       snmp_sess_perror("ack", &session);  
  71.       SOCK_CLEANUP;  
  72.       exit(1);  
  73.     }  
  74.       
  75.     /* 
  76.      * Create the PDU for the data for our request. 
  77.      *   1) We're going to GET the system.sysDescr.0 node. 
  78.      */  
  79.     pdu = snmp_pdu_create(SNMP_MSG_GET);  
  80.     anOID_len = MAX_OID_LEN;  
  81.     if (!snmp_parse_oid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len)) {  
  82.       snmp_perror(".1.3.6.1.2.1.1.1.0");  
  83.       SOCK_CLEANUP;  
  84.       exit(1);  
  85.     }  
  86. #if OTHER_METHODS  
  87.     /* 
  88.      *  These are alternatives to the 'snmp_parse_oid' call above, 
  89.      *    e.g. specifying the OID by name rather than numerically. 
  90.      */  
  91.     read_objid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len);  
  92.     get_node("sysDescr.0", anOID, &anOID_len);  
  93.     read_objid("system.sysDescr.0", anOID, &anOID_len);  
  94. #endif  
  95.     snmp_add_null_var(pdu, anOID, anOID_len);  
  96.     
  97.     /* 
  98.      * Send the Request out. 
  99.      */  
  100.     status = snmp_synch_response(ss, pdu, &response);  
  101.     /* 
  102.      * Process the response. 
  103.      */  
  104.     if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) {  
  105.       /* 
  106.        * SUCCESS: Print the result variables 
  107.        */  
  108.       for(vars = response->variables; vars; vars = vars->next_variable)  
  109.         print_variable(vars->name, vars->name_length, vars);  
  110.       /* manipuate the information ourselves */  
  111.       for(vars = response->variables; vars; vars = vars->next_variable) {  
  112.         if (vars->type == ASN_OCTET_STR) {  
  113.       char *sp = (char *)malloc(1 + vars->val_len);  
  114.       memcpy(sp, vars->val.string, vars->val_len);  
  115.       sp[vars->val_len] = '/0';  
  116.           printf("value #%d is a string: %s/n", count++, sp);  
  117.       free(sp);  
  118.     }  
  119.         else  
  120.           printf("value #%d is NOT a string! Ack!/n", count++);  
  121.       }  
  122.     } else {  
  123.       /* 
  124.        * FAILURE: print what went wrong! 
  125.        */  
  126.       if (status == STAT_SUCCESS)  
  127.         fprintf(stderr, "Error in packet/nReason: %s/n",  
  128.                 snmp_errstring(response->errstat));  
  129.       else if (status == STAT_TIMEOUT)  
  130.         fprintf(stderr, "Timeout: No response from %s./n",  
  131.                 session.peername);  
  132.       else  
  133.         snmp_sess_perror("snmpdemoapp", ss);  
  134.     }  
  135.     /* 
  136.      * Clean up: 
  137.      *  1) free the response. 
  138.      *  2) close the session. 
  139.      */  
  140.     if (response)  
  141.       snmp_free_pdu(response);  
  142.     snmp_close(ss);  
  143.     SOCK_CLEANUP;  
  144.     return (0);  
  145. /* main() */  

makefile:

[cpp]  view plain  copy
  1. #  
  2. # Warning: you may need more libraries than are included here on the  
  3. # build line.  The agent frequently needs various libraries in order  
  4. # to compile pieces of it, but is OS dependent and we can't list all  
  5. # the combinations here.  Instead, look at the libraries that were  
  6. # used when linking the snmpd master agent and copy those to this  
  7. # file.  
  8. #  
  9. CC=gcc  
  10. OBJS1=snmpdemoapp.o  
  11. OBJS2=example-demon.o nstAgentSubagentObject.o  
  12. OBJS3=asyncapp.o  
  13. TARGETS=example-demon snmpdemoapp asyncapp  
  14. CFLAGS=-I. `net-snmp-config --cflags`  
  15. BUILDLIBS=`net-snmp-config --libs`  
  16. BUILDAGENTLIBS=`net-snmp-config --agent-libs`  
  17. # shared library flags (assumes gcc)  
  18. DLFLAGS=-fPIC -shared  
  19. all: $(TARGETS)  
  20. snmpdemoapp: $(OBJS1)  
  21.     $(CC) -o snmpdemoapp $(OBJS1) $(BUILDLIBS)  
  22. asyncapp: $(OBJS3)  
  23.     $(CC) -o asyncapp $(OBJS3) $(BUILDLIBS)  
  24. example-demon: $(OBJS2)  
  25.     $(CC) -o example-demon $(OBJS2)  $(BUILDAGENTLIBS)  
  26. clean:  
  27.     rm $(OBJS2) $(OBJS2) $(TARGETS)  
  28. nstAgentPluginObject.so: nstAgentPluginObject.c Makefile  
  29.     $(CC) $(CFLAGS) $(DLFLAGS) -c -o nstAgentPluginObject.o nstAgentPluginObject.c  
  30.     $(CC) $(CFLAGS) $(DLFLAGS) -o nstAgentPluginObject.so nstAgentPluginObject.o  


 

[cpp]  view plain  copy
  1. 首先,必须安装net-snmp工具,里面包含有代理软件(在被管理的远端主机上相应我们的请求),管理端(在本地接收信息),和我们开发必须的库和头文件。所以在我们的程序中包含以下头文件:   
  2.   
  3. #include <net-snmp/net-snmp-config.h>   
  4.   
  5. #include <net-snmp/net-snmp-includes.h>   
  6.   
  7.   
  8.   
  9.   
  10. 下一步,我们考虑到版本问题,我们做一些代码编译的宏定义,不过我们默认是SNMPv3,第3版本比以前的版本复杂,也更安全。   
  11.   
  12. /* change the word "define" to "undef" to try the (insecure) SNMPv1 version */  
  13. #define DEMO_USE_SNMP_VERSION_3  
  14.   
  15. #ifdef DEMO_USE_SNMP_VERSION_3  
  16. #include "net-snmp/transform_oids.h"  
  17. const char *our_v3_passphrase = "The Net-SNMP Demo Password";  
  18. #endif  
  19.   
  20.   
  21.   
  22. 下一步定义主函数:   
  23.   
  24.   
  25.   
  26.   
  27. main() {  
  28.   
  29.   
  30.   
  31.   
  32.   
  33. 第一个我们要声明的变量:   
  34.   
  35.   
  36.   
  37.   
  38. struct snmp——session  保存远端主机的信息,我们要声明两个,一个用于填写远端信息,一个用于库返回的指针;   
  39.   
  40. strcut  snmp_pdu: 用于我们要发送给远端主机的结构信息,我们也要声明两个,另一个接收返回信息。   
  41.   
  42. oid: 一个oid 保存我们希望接收到的信息的位置(远端主机的节点位置)   
  43.   
  44. struct variable_list:  保存我们想要通过snmp操作的变量。   
  45.   
  46. struct snmp_session session, *ss;  
  47. struct snmp_pdu *pdu;  
  48. struct snmp_pdu *response;  
  49.   
  50. oid anOID[MAX_OID_LEN];  
  51. size_t anOID_len = MAX_OID_LEN;  
  52.   
  53. struct variable_list *vars;  
  54. int status;  
  55.   
  56.   
  57.   
  58. 初始化化库:   
  59.   
  60. /*  
  61.  
  62. * Initialize the SNMP library 
  63. */  
  64. init_snmp("snmpapp");  
  65.   
  66.   
  67.   
  68. 下一步,我们初始化了一个session描述了我们希望通信的会话信息(包括本版信息,怎么样认证等),完整的session在   
  69.   
  70. net-snmp/snmp_api.h中有原型。这里我们默认用的是第三版。   
  71.   
  72.   
  73.   
  74.   
  75. /*  
  76.  
  77. * Initialize a "session" that defines who we're going to talk to 
  78. */  
  79. snmp_sess_init( &session ); /*初始化会话 */  
  80. session.peername = "test.net-snmp.org";  /* 
  81.  
  82. /* 设置验证参数 */  
  83.   
  84. #ifdef DEMO_USE_SNMP_VERSION_3  
  85.   
  86. /* 用第三版 */  
  87.   
  88. /* 设置 SNMP version number */  
  89. session.version=SNMP_VERSION_3;  
  90.   
  91. /* 设置 SNMPv3用户名*/  
  92. session.securityName = strdup("MD5User");  
  93. session.securityNameLen = strlen(session.securityName);  
  94.   
  95. /* 设置认证安全等级, 但是不加密*/  
  96. session.securityLevel = SNMP_SEC_LEVEL_AUTHNOPRIV;  
  97.   
  98. /* 设置认证方法 */  
  99. session.securityAuthProto = usmHMACMD5AuthProtocol;  
  100. session.securityAuthProtoLen = sizeof(usmHMACMD5AuthProtocol)/sizeof(oid);  
  101. session.securityAuthKeyLen = USM_AUTH_KU_LEN;  
  102.   
  103. /* set the authentication key to a MD5 hashed version of our 
  104. passphrase "The Net-SNMP Demo Password" (which must be at least 8 
  105. characters long) */  
  106. if (generate_Ku(session.securityAuthProto,  
  107. session.securityAuthProtoLen,  
  108. (u_char *) our_v3_passphrase, strlen(our_v3_passphrase),  
  109. session.securityAuthKey,  
  110. &session.securityAuthKeyLen) != SNMPERR_SUCCESS) {  
  111. snmp_perror(argv[0]);  
  112. snmp_log(LOG_ERR,  
  113. "Error generating Ku from authentication pass phrase. /n");  
  114. exit(1);  
  115. }  
  116.   
  117. #else /* we'll use the insecure (but simplier) SNMPv1 */  
  118.   
  119. /* set the SNMP version number */  
  120. session.version = SNMP_VERSION_1;  
  121.   
  122. /* set the SNMPv1 community name used for authentication */  
  123. session.community = "demopublic";  
  124. session.community_len = strlen(session.community);  
  125.   
  126. #endif /* SNMPv1 */  
  127.   
  128.   
  129.   
  130.   
  131.   
  132.   
  133. 在我们建立会话之后,我们要打开它,返回一个指向另一个会话的指针,以后的操作就在返回的会话上完成。   
  134.   
  135. /* windows32 specific initialization (is a noop on unix) */windows32 需要的初始化socket,linux下的不用  
  136. SOCK_STARTUP;  
  137.   
  138. /* 
  139. * 打开会话 
  140. */  
  141. ss = snmp_open(&session); /* 连接会话 */  
  142.   
  143.   
  144. /*如果打开失败,打印错误原因*/   
  145.   
  146. if (!ss) {   
  147.   
  148. snmp_perror("ack");  
  149. snmp_log(LOG_ERR, "something horrible happened!!!/n");  
  150. exit(2);  
  151. }  
  152.   
  153.   
  154.   
  155.   
  156.   
  157. 下一步,我们创建pdu用于打包我们发送请求的信息,在这里我们建一个SNMP-GET pdu  (是snmpget program用的,也就是管理端用的)   
  158.   
  159. /* 
  160. * 创建pdu 
  161. */   
  162.   
  163. 下面这段保持原文好点,我翻译的不好  
  164. pdu = snmp_pdu_create(SNMP_MSG_GET);  
  165.   
  166.   
  167. So, let's fill it with our requested oid. Let's get the system.sysDescr.0 variable for this example. There are numerious ways you could create the oid in question. You could put in the numerical unsigned integer values yourself into the anOID array we created above, or you could use one of the following function calls to do it. We recommend the first one (get_node), as it is the most powerful and accepts more types of OIDs.   
  168.   
  169. read_objid(".1.3.6.1.2.1.1.1.0", anOID, &anOID_len);  
  170.   
  171. #if OTHER_METHODS  
  172. get_node("sysDescr.0", anOID, &anOID_len);  
  173. read_objid("system.sysDescr.0", anOID, &anOID_len);  
  174. #endif  
  175.   
  176.   
  177.   
  178. So we add this oid, with a NULL value to the PDU using the following statement: (all oids should be paired with a NULL value for outgoing requests for information. For an SNMP-SET pdu, we'd put in the value we wanted to set the oid to).   
  179.   
  180. snmp_add_null_var(pdu, anOID, anOID_len);  
  181.   
  182.   
  183.   
  184. 通过上面返回的会话指针,发送我们的请求信息pdu,返回一个状态是int型的,还返回一个pdu信息,用pdu指针指向它,它存有我们需要的信息。   
  185.   
  186. /* 
  187. * Send the Request out. 
  188. */  
  189. status = snmp_synch_response(ss, pdu, &response);  
  190.   
  191.   
  192.   
  193.   
  194.   
  195.   
  196. /*先检查信息,假设我们的请求成功返回,如果不是就打印错误信息。*/   
  197.   
  198.   
  199. if (status == STAT_SUCCESS && response->errstat == SNMP_ERR_NOERROR) {  
  200. /* 
  201. * SUCCESS: Print the result variables 
  202. */  
  203.   
  204.   
  205.   
  206. 用print_variable()输出pdu的变量到终端。   
  207.   
  208. for(vars = response->variables; vars; vars = vars->next_variable)  
  209. print_variable(vars->name, vars->name_length, vars);  
  210.   
  211.   
  212.   
  213. Then, for kicks, lets get the information and manipulate it ourselves (checking to make sure its the type we're expecting (a string) first):(对获得的信息的操作,检验它的类型)   
  214.   
  215. /* manipulate the information ourselves */  
  216. for(vars = response->variables; vars; vars = vars->next_variable) {  
  217. int count=1;  
  218. if (vars->type == ASN_OCTET_STR) {  
  219. char *sp = (char *)malloc(1 + vars->val_len);  
  220. memcpy(sp, vars->val.string, vars->val_len);  
  221. sp[vars->val_len] = '/0';  
  222. printf("value #%d is a string: %s/n", count++, sp);  
  223. free(sp);  
  224. }  
  225. else  
  226. printf("value #%d is NOT a string! Ack!/n", count++);  
  227. }  
  228.   
  229.   
  230.   
  231. /*如果有错误的话,输出错误信息*/   
  232.   
  233. else {  
  234. /* 
  235. * FAILURE: print what went wrong! 
  236. */  
  237.   
  238. if (status == STAT_SUCCESS)  
  239. fprintf(stderr, "Error in packet/nReason: %s/n",  
  240. snmp_errstring(response->errstat));  
  241. else  
  242. snmp_sess_perror("snmpget", ss);  
  243.   
  244. }  
  245.   
  246.   
  247.   
  248.   
  249.   
  250.   
  251. /*最后,要释放资源snmp_free_pdu(),用退出函数snmp_close()安全退出:*/   
  252.   
  253. /* 
  254. * Clean up: 
  255. * 1) free the response. 
  256. * 2) close the session. 
  257. */  
  258. if (response)  
  259. snmp_free_pdu(response);  
  260. snmp_close(ss);  
  261.   
  262. /* windows32 specific cleanup (is a noop on unix) */  
  263. SOCK_CLEANUP;  
  264.   
  265. /* main() */  
  266. 运行makefile编译:   
  267.   
  268. % make snmpdemoapp   
  269.   
  270. cc -I/usr/local/include -g -c snmpdemoapp.c -o snmpdemoapp.o  
  271. cc -o snmpdemoapp snmpdemoapp.o -lnetsnmp  
  272.   
  273.   
  274.   
  275. 运行:   
  276.   
  277. % ./snmpdemoapp   
  278. system.sysDescr.0 = HP-UX net-snmp B.10.20 A 9000/715  
  279. value #1 is a string: HP-UX net-snmp B.10.20 A 9000/715  
深度学习是机器学习的一个子领域,它基于人工神经网络的研究,特别是利用多层次的神经网络来进行学习和模式识别。深度学习模型能够学习数据的高层次特征,这些特征对于图像和语音识别、自然语言处理、医学图像分析等应用至关重要。以下是深度学习的一些关键概念和组成部分: 1. **神经网络(Neural Networks)**:深度学习的基础是人工神经网络,它是由多个层组成的网络结构,包括输入层、隐藏层和输出层。每个层由多个神经元组成,神经元之间通过权重连接。 2. **前馈神经网络(Feedforward Neural Networks)**:这是最常见的神经网络类型,信息从输入层流向隐藏层,最终到达输出层。 3. **卷积神经网络(Convolutional Neural Networks, CNNs)**:这种网络特别适合处理具有网格结构的数据,如图像。它们使用卷积层来提取图像的特征。 4. **循环神经网络(Recurrent Neural Networks, RNNs)**:这种网络能够处理序列数据,如时间序列或自然语言,因为它们具有记忆功能,能够捕捉数据中的时间依赖性。 5. **长短期记忆网络(Long Short-Term Memory, LSTM)**:LSTM 是一种特殊的 RNN,它能够学习长期依赖关系,非常适合复杂的序列预测任务。 6. **生成对抗网络(Generative Adversarial Networks, GANs)**:由两个网络组成,一个生成器和一个判别器,它们相互竞争,生成器生成数据,判别器评估数据的真实性。 7. **深度学习框架**:如 TensorFlow、Keras、PyTorch 等,这些框架提供了构建、训练和部署深度学习模型的工具和库。 8. **激活函数(Activation Functions)**:如 ReLU、Sigmoid、Tanh 等,它们在神经网络中用于添加非线性,使得网络能够学习复杂的函数。 9. **损失函数(Loss Functions)**:用于评估模型的预测与真实值之间的差异,常见的损失函数包括均方误差(MSE)、交叉熵(Cross-Entropy)等。 10. **优化算法(Optimization Algorithms)**:如梯度下降(Gradient Descent)、随机梯度下降(SGD)、Adam 等,用于更新网络权重,以最小化损失函数。 11. **正则化(Regularization)**:技术如 Dropout、L1/L2 正则化等,用于防止模型过拟合。 12. **迁移学习(Transfer Learning)**:利用在一个任务上训练好的模型来提高另一个相关任务的性能。 深度学习在许多领域都取得了显著的成就,但它也面临着一些挑战,如对大量数据的依赖、模型的解释性差、计算资源消耗大等。研究人员正在不断探索新的方法来解决这些问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值