我有以下代码,它可以在 snmp v2 上批量获取整个 1.3.6.1 OIDRoot 的特定 IP。然后我将结果写入 csv 文件。问题是它只写入最后一个结果行而不是所有行。我是 C# 新手,并且仍在努力学习这门语言。你能告诉我我的代码做错了什么吗?
private void SNMP_WALK(object sender, EventArgs e)
{
OctetString community = new OctetString("public");
AgentParameters param = new AgentParameters(community);
param.Version = SnmpVersion.Ver2;
string deviceMac = null;
string devicePort = null;
string deviceHCID = null;
XmlDocument doc = new XmlDocument();
doc.Load("devices.xml");
foreach (XmlElement dev in doc.SelectNodes("/data/devices/device"))
{
deviceMac = dev.Attributes["mac"].Value;
devicePort = dev.Attributes["port"].Value;
deviceHCID = dev.Attributes["hcid"].Value;
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
if (deviceHCID != null)
{
try
{
IpAddress agent = new IpAddress(devicePort);
UdpTarget target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
Oid rootOid = new Oid("1.3.6.1");
Oid lastOid = (Oid)rootOid.Clone();
Pdu pdu = new Pdu(PduType.GetBulk);
pdu.NonRepeaters = 0;
pdu.MaxRepetitions = 20;
while (lastOid != null)
{
if (pdu.RequestId != 0)
{
pdu.RequestId += 1;
}
pdu.VbList.Clear();
pdu.VbList.Add(lastOid);
SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
if (result != null)
{
if (result.Pdu.ErrorStatus != 0)
{
Console.WriteLine("Error in SNMP reply. Error {0} index {1}",
result.Pdu.ErrorStatus,
result.Pdu.ErrorIndex);
lastOid = null;
break;
}
else
{
foreach (Vb v in result.Pdu.VbList)
{
if (rootOid.IsRootOf(v.Oid))
{
string deviceHCIDw = deviceHCID;
ostrm = new FileStream("snmp_dump.csv", FileMode.OpenOrCreate, FileAccess.Write);
writer = new StreamWriter(ostrm);
Console.SetOut(writer);
Console.WriteLine("{0} {1} ({2}): {3}",
deviceHCIDw.ToString(),
v.Oid.ToString(),
SnmpConstants.GetTypeName(v.Value.Type),
v.Value.ToString());
Console.SetOut(oldOut);
writer.Close();
ostrm.Close();
Console.WriteLine("Done");
if (v.Value.Type == SnmpConstants.SMI_ENDOFMIBVIEW)
lastOid = null;
else
lastOid = v.Oid;
}
else
{
lastOid = null;
}
}
}
}
else
{
Console.WriteLine("No response received from SNMP agent.");
}
}
target.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
这是 CSV 文件内容。
HCID01318 1.3.6.1.6.3.18.1.1.1.8.116.48.48.48 (Unknown): SNMP End-of-MIB-View
00 A1 C0 A8 0A FC
91 5E
d-only
PRINTER;DES:CANON 640NPCL_PS;
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
预先感谢您的帮助。
使用
FileMode.Append
,或在第一个 foreach
循环之前打开文件。您实际上是在覆盖每个响应的文件。