编译snmp++的包
调用snmp++.lib实现信息获取_哔哩哔哩_bilibili
代码:
#include <iostream>
#include <libsnmp.h>
#include <vector>
#include <fstream>
#include <string>
#include "snmp_pp/snmp_pp.h"
//#define _NO_LOGGING
#ifdef WIN32
#define strcasecmp _stricmp
#endif
#ifdef SNMP_PP_NAMESPACE
using namespace Snmp_pp;
#endif
using namespace std;
using namespace Snmp_pp;
typedef struct {
string aa;
string bb;
string cc;
}CON;
vector<CON> readTxt(string path) {
vector<CON> res;
ifstream file(path);
string line;
CON a;
getline(file, line);
line = line.substr(line.find('=') + 1);
a.aa = line;
while (getline(file,line))
{
line= line.substr(line.find('=') + 1);
a.bb = line;
getline(file, line);
line = line.substr(line.find('=') + 1);
a.cc = line;
res.push_back(a);
}
return res;
}
vector<string> getSnmpValue(vector<CON> a) {
vector<string> res;
int status;
Snmp::socket_startup(); // Initialize the socket subsystem
// Create an SNMP++ session
Snmp snmp(status);
if (status != SNMP_CLASS_SUCCESS)
{
cout << "SNMP++ Session creation failed." << endl;
return vector<string>();
}
for (int i = 0; i < a.size(); i++)
{
// Set the target address
UdpAddress targetAddress(a[i].bb.c_str());
// Create the target using the target address and community string
CTarget target(targetAddress);
target.set_version(version2c); // Use SNMPv2c
target.set_retry(3); // Set the number of retries
target.set_timeout(1000); // Set the timeout (milliseconds)
target.set_readcommunity(a[i].aa.c_str());
// Create a PDU object for the SNMP GET request
Pdu pdu;
pdu.set_type(sNMP_PDU_GET);
pdu += Vb(a[i].cc.c_str()); // Add the OID to retrieve
// Send the SNMP GET request
status = snmp.get(pdu, target);
if (status == SNMP_CLASS_SUCCESS)
{
// Check the response PDU for errors
if (pdu.get_error_status() == SNMP_ERROR_SUCCESS)
{
// Iterate through the received variable bindings
for (int i = 0; i < pdu.get_vb_count(); i++)
{
Vb vb;
pdu.get_vb(vb, i);
std::string value = vb.get_printable_value();
res.push_back(value); // 将值添加到容器中
//cout << "OID: " << vb.get_printable_oid() << endl;
//cout << "Value: " << vb.get_printable_value() << endl;
}
}
else
{
cout << "Error in response PDU: " << endl;
}
}
else
{
cout << "SNMP++ GET request failed: " << snmp.error_msg(status) << endl;
}
}
Snmp::socket_cleanup(); // Shut down the socket subsystem
return res;
}
int main()
{
string p = "D:\\ALearn\\snmp\\testSnmpJJ\\1.txt";
vector<CON> a = readTxt(p);
/*for (int i = 0; i < a.size(); i++)
{
cout << a[i].aa << endl;
cout << a[i].bb << endl;
cout << a[i].cc << endl;
}*/
vector<string> b = getSnmpValue(a);
for (int i = 0; i < b.size(); i++)
{
cout <<"value===="<< b[i] << endl;
}
return 0;
}
配置文件:
运行截图:(一定要运行snmp服务)