MRTG - National Chi Nan University

Download Report

Transcript MRTG - National Chi Nan University

SNMP Programming
Yen-Cheng Chen
SNMP Agents





127.0.0.1 (localhost)
10.32.6.3 (D-link Switch)
10.32.6.4 (Cisco Layer-3 Switch)
10.32.6.8 (Cisco AP)
10.32.2.30 (HP Printer)
Community Name: nm2013
Project

MRTG


php SNMP


75~90
Java


70~85
80~90
Java + JFreeChart

85~95
WebNMS SNMP API
Outline

MRTG

Network Service Monitoring Using Sockets

WebNMS/AdventNet SNMP API

JFreeChart

Perl SNMP
MRTG
• Multi Router Traffic Grapher (Oeticker and Rand)
• http://oss.oetiker.ch/mrtg/
• Generates graphic presentation of traffic on Web
• Daily view
• Weekly view
• Monthly view
• Yearly view
Installation (Windows)

Perl (ActivePerl)
 http://www.activestate.com/
 http://www.activestate.com/activeperl/downloads
 http://ycchen.im.ncnu.edu.tw/ActivePerl-5.16.3.1603-MSWin32x86-296746.msi

MRTG




http://oss.oetiker.ch/mrtg/
http://oss.oetiker.ch/mrtg/download.en.html
http://ycchen.im.ncnu.edu.tw/mrtg-2.17.4.zip
Path

C:\Perl\bin;…

Configuration file: mrtg.cfg
perl mrtg mrtg.cfg

http://oss.oetiker.ch/mrtg/doc/mrtg-reference.en.html

Installation (cont.)
wperl c:\mrtg\bin\mrtg c:\mrtg\cfg\mrtg.cfg
cfgmaker
• automatically generate a configuration file
• perl cfgmaker community@host > mrtg.cfg
indexmaker
• automatically generate an index web page
• perl indexmaker mrtg.cfg > index.html
mrtg.cfg
RunAsDaemon: yes
Language: big5
WorkDir: c:\Inetpub\wwwroot\mrtgdata
Htmldir: c:\www\mrtg
Imagedir: c:\www\mrtg\images
Logdir: c:\mrtglogs
IconDir: c:\www\mrtgicons
Forks: 4
(sec)
Refresh: 600
Interval: 10
(分鐘)
WriteExpires: Yes
(sysName, sysUpTime)
NoMib2: Yes
SingleRequest: Yes (Variable Binding List)
LoadMIBs: c:\mibs\mib2.mib,c:\mibs\ether.mib
mrtg.cfg (cont.)
trunk2.html
Target[trunk2]: 2:[email protected]:
SetEnv[trunk2]: MRTG_INT_IP="“MRTG_INT_DESCR="FastEthernet0/1"
MaxBytes[trunk2]: 12500000
Title[trunk2]: Traffic Analysis for 2 -- cnclab
PageTop[trunk2]: <H1>Traffic Analysis for 2 -- cnclab</H1>
<TABLE>
<TR><TD>System:</TD><TD>cnclab in R409</TD></TR>
<TR><TD>Maintainer:</TD><TD>mentor</TD></TR>
<TR><TD>Description:</TD><TD>FastEthernet0/1 </TD></TR>
<TR><TD>ifType:</TD><TD>ethernetCsmacd (6)</TD></TR>
<TR><TD>ifName:</TD><TD>Fa0/1</TD></TR>
<TR><TD>Max Speed:</TD><TD>12.5 MBytes/s</TD></TR>
</TABLE>
Options[trunk2]: growright, bits
Target[xxx]:

port:community@router
2:[email protected]
-1:[email protected]

OID_1&OID_2:community@router
1.3.6.1.4.1.11.2.1&1.3.6.1.4.1.11.5.1:public@myrouter
ifInErrors.1&ifOutErrors.1:public@myrouter

Multi Target Syntax
2:public@wellfleetA + 1:public@wellfleetA
Intranet 2
R2
SNMP Agent
R1
NMS
Intranet 1
External Monitoring Scripts
Target[rr1]: `perl C:\perl\df2mrtg.pl var1 var2`
The external command must return 4 lines of output:
Line 1
current state of the first variable, normally 'incoming
bytes count'
Line 2
current state of the second variable, normally 'outgoing
bytes count'
Line 3
string (in any human readable format), telling the uptime of
the target.
Line 4
string, telling the name of the target.
•




Configuration
Target[MyDisk]: `java -cp .;C:/SomeDir/commons-io-2.0.1.jar DiskSpace`
MaxBytes[MyDisk]: 42154528
Title[MyDisk]: PC-YCChen's Disk Free Space
PageTop[MyDisk]: <h1>PC-YCChen's Disk Free Space</h1>
YLegend[MyDisk]: KBytes
Options[MyDisk]: growright, gauge
DiskSpace.java
http://ycchen.im.ncnu.edu.tw/nm/DiskSpace.zip
import java.io.IOException;
import java.util.*;
import java.text.SimpleDateFormat;
import org.apache.commons.io.FileSystemUtils;
public class DiskSpace {
public static void main(String[] args) {
Date now= new Date();
SimpleDateFormat sdf = new SimpleDateFormat();
try {
long freeDiskSpaceC = Math.round(FileSystemUtils.freeSpaceKb("C:"));
long freeDiskSpaceD = Math.round(FileSystemUtils.freeSpaceKb("D:"));
System.out.println(freeDiskSpaceC);
System.out.println(freeDiskSpaceD);
System.out.println(sdf.format(now));
System.out.println("PC-YCChen at R5041");
} catch (IOException e) {
e.printStackTrace();
}
}
javac -cp .;./commons-io-2.0.1.jar DiskSpace.java
}
ifIndex problem





Interface by IP
/1.2.3.4:[email protected]
Interface by Description
\My-If2:[email protected]
Interface by Name
#ifName1:[email protected]
Interface by Ethernet Address
!0-f-bb-05-71-22:[email protected]
Interface by Type
%13:[email protected]
Options
Options[trunck2]: growright, gauge, bits
•
•
•
•
•
growrights
•
The graph grows to the left by default. This option will make the
graph grow to the right
gauge
•
For data type “gauge”. To monitor things like disk space, processor
load, temperature
bits
absolute
•
for counter type data sources which reset their value when they are
read.
Other useful options:
•
logscale, perminute, perhour, nopercent, dorelpercent,
unknaszero, withzeroes
Make MRTG run all the time
Yen-Cheng Chen
IM, NCNU
Taiwan
C:\perl\bin\wperl mrtg --logging=eventlog mrtg.cfg
Add the option
RunAsDaemon: yes
to your mrtg.cfg
1
3
2
1
2
Network Service Monitoring



Usually, we use ‘ping’ to detect whether a host is
alive.
A host is alive, but its network service may be down.
Try to establish a TCP connection with the network
service.


If the connection is established, the network service is still
running.
Otherwise, the service is down.
import java.net.*;
java PortMonitor host port1 port2 …
import java.io.*;
public class PortMonitor {
public static void main(String[] args) {
String host = args[0] ;
String ports[] = new String [args.length - 1];
for (int i=1; i<args.length; i++) ports[i-1] = args[i];
InetAddress address = null;
try {
address = InetAddress.getByName(host);
} catch (UnknownHostException e) {
System.err.println("Invaild Host Name:" + host);
System.exit(1); }
int port = 0 ;
for (int i = 0; i < ports.length; i++) {
port = Integer.parseInt(ports[i]);
Socket s = null;
try {
s = new Socket(address,port);
System.out.println("Port: "+port +" is Up.");
} catch(IOException e) {
System.out.println("Port: "+port +" is down.");
} finally {
if (s != null) {
try {
s.close();
} catch(IOException e) {
System.err.println("Can’t close on port " + port);}
}
}
}
}
}
AdventNet SNMP API Architecture
SNMP High Level API
Installation

JDK 1.2 and later including JDK 1.4
http://www.oracle.com/technetwork/java/javase/downloads/index.html

WebNMS/AdventNet SNMP API 4
http://www.webnms.com/snmp/80636898/WebNMS_SNMPAPI_StandardEdition.zip

Update Environment Variables

PATH

CLASSPATH

Javac SnmpExample1.java

Java SnmpExample1
Environment Variables Setting
開始  控制台
Path
C:\j2sdk1.4.2_05\bin;
CLASSPATH
Old:
C:\Program Files\Java\j2re1.4.2_08\lib\ext\QTJava.zip
New:
C:\Program Files\Java\j2re1.4.2_08\lib\ext\QTJava.zip;.;
C:\AdventNet\SNMPAPI\jars\AdventNetLogging.jar;
C:\AdventNet\SNMPAPI\jars\AdventNetSnmp.jar
Get
java SnmpGet host oid1 oid2 …
import com.adventnet.snmp.beans.*;
public class SnmpGet {
public static void main(String args[]) {
String remoteHost = args[0];
SnmpTarget target = new SnmpTarget();
target.setTargetHost(remoteHost);
target.setCommunity("public");
String oids[] = new String [args.length - 1];
for (int i=1; i<args.length; i++) oids[i-1] = args[i];
target.setObjectIDList(oids);
String result[] = target.snmpGetList();
for (int i=0;i<oids.length;i++) {
System.out.println("OBJECT ID: "+target.getObjectID(i));
System.out.println("Response: "+result[i]);
}
System.exit(0);
}
java SnmpGet 163.22.20.43 .1.3.6.1.2.1.1.1.0
}
GetNext
java SnmpGetNext host oid1 oid2 …
import com.adventnet.snmp.beans.*;
public class SnmpGetNext {
public static void main(String args[]) {
String remoteHost = args[0];
SnmpTarget target = new SnmpTarget();
target.setTargetHost(remoteHost);
target.setCommunity("public");
String oids[] = new String [args.length - 1];
for (int i=1; i<args.length; i++) oids[i-1] = args[i];
target.setObjectIDList(oids);
String result[] = target.snmpGetNextList();
for (int i=0;i<oids.length;i++) {
System.out.println("OBJECT ID: "+target.getObjectID(i));
System.out.println("Response: "+result[i]);
}
System.exit(0);
}
}
import com.adventnet.snmp.beans.*;
public class snmpnetstat {
Get a Table
public static void main(String args[]) {
String remoteHost = args[0];
java snmpnetstat host community
String community = args[1];
SnmpTable table = new SnmpTable();
table.setTargetHost(remoteHost);
table.setCommunity(community);
try {
table.loadMibs("RFC1213-MIB");
table.setTableOID("tcpConnTable");
}catch (Exception ex) {}
try { Thread.sleep(10000); } // allow some time to get all rows
catch (InterruptedException ex) {}
System.out.println("<table align=center border=5 width=80%><tr>");
for (int i=0;i<table.getColumnCount();i++) // print column names
System.out.println("<th>"+table.getColumnName(i)+"</th>");
System.out.println("</tr>");
for (int i=0;i<table.getRowCount();i++) {
System.out.println("<tr bgColor=lightyellow>");
for (int j=0;j<table.getColumnCount();j++)
System.out.println("<td>" +table.getValueAt(i,j)+"</td>");
System.out.println("</tr>");
}
System.out.println("</table>");
System.exit(0);
}
}
import com.adventnet.snmp.beans.*;
Set
public class SnmpSet {
public static void main(String args[]) {
String remoteHost = args[0];
String comm = args[1];
String mibs = args[2];
String OID = args[3];
java SnmpSet hostname comm mibs
String value = args[4];
SnmpTarget target = new SnmpTarget();
target.setTargetHost(remoteHost);
target.setCommunity(comm);
target.setObjectID(OID);
try { target.loadMibs(mibs); }
catch (Exception ex) { System.err.println("Error loading MIBs: "+ex); }
try {
String result = target.snmpSet(value);
System.out.println("Response PDU from " +target.getTargetHost());
System.out.println("Community: " + target.getCommunity());
System.out.println("OBJECT ID: "+target.getObjectID());
System.out.println("Response: "+result);
} catch (Exception e) {
System.err.println("Set Error: "+e.getMessage());
}
System.exit(0);
}
}
oid value
public class trapd {
public static void main(String args[]) {
SnmpTrapReceiver receiver = new SnmpTrapReceiver();
receiver.setCommunity("communityName");
Trap Listener
receiver.setPort(162);
TrapListener listener = new TrapListener() {
java trapd
public void receivedTrap(TrapEvent trap) {
String enterprise = trap.getEnterprise();
String agentAddr = trap.getAgentAddress();
int genericTrap = trap.getTrapType();
int specificTrap = trap.getSpecificType();
long trapTimestamp = trap.getUpTime();
// print the above trap PDU fields here
SnmpPDU trapPDU = trap.getTrapPDU();
Vector varBinds = trapPDU.getVariableBindings();
int numVB = varBinds.size();
for (int i=0; i<numVB; i++) {
SnmpVarBind vb = (SnmpVarBind) varBinds.elementAt(i);
System.out.print(vb.getObjectID().toString()+": ");
System.out.println(vb.getVariable().toString());
}
import com.adventnet.snmp.beans.*;
}
import com.adventnet.snmp.snmp2.*;
};
import java.util.*;
receiver.addTrapListener(listener);
}}
Other Examples




snmpwalkv1.java
getTable.java
setIfAdmS.java
traPoller.java
http://ycchen.im.ncnu.edu.tw/nm/java-ex.zip
JFreeChart
- http://www.jfree.org/jfreechart/
Yen-Cheng Chen
IM, NCNU
Taiwan
What is JFreeChart?

JFreeChart is a free Java class library for generating
charts, including:
* pie charts (2D and 3D);
* bar charts (regular and stacked, with an optional 3D effect);
* line and area charts;
* scatter plots and bubble charts;
* time series, high/low/open/close charts and candle stick charts;
* combination charts;
* Pareto charts;
* Gantt charts;
* wind plots, meter charts and symbol charts;
* wafer map charts
Useful WWW Resources

http://www.jfree.org/jfreechart/

Download


Documentation



http://ncu.dl.sourceforge.net/project/jfreechart/2.%20Docume
ntation/1.0.5/jfreechart-1.0.5-install.pdf
http://www.jfree.org/jfreechart/api/gjdoc/index.html
Demo


http://sourceforge.net/projects/jfreechart/files/1. JFreeChart/1.0.13/jfreechart-1.0.13.zip
http://www.jfree.org/jfreechart/jfreechart-1.0.5-demo.jnlp
Demo Program Source

http://www.koders.com/default.aspx?s=JFreeChart&btn=Sea
rch&la=*&li=*
Environment Variables

CLASSPATH






C:\Java\jdk1.5.0_06\lib\tools.jar
C:\jfreechart-1.0.1\lib\jfreechart1.0.1.jar
C:\jfreechart-1.0.1\lib\jcommon-1.0.0.jar
JAVA_HOME=C:\Java\jdk1.5.0_06
JAVA_HOME_DIR=C:\Java\jdk1.5.0_06
Path

C:\Java\jdk1.5.0_06\bin
Auto Scaling
http://ycchen.im.ncnu.edu.tw/nm/chart-ex.zip
Perl SNMP

Perl modules:


SNMP_Session.pm
BER.pm
http://ycchen.im.ncnu.edu.tw/nm/perlSNMP.zip

Other modules:
http://cpan.org/modules/by-module/SNMP/
get.pl (1/2)
#!/usr/local/bin/perl
require 5.003;
use SNMP_Session "0.52";
use BER "0.50";
$SNMPDEBUG=0;
$DEBUG=0;
%snmpget::OIDS =
('sysDescr' => '1.3.6.1.2.1.1.1.0',
'sysObjectID' => '1.3.6.1.2.1.1.2.0',
'sysUptime' => '1.3.6.1.2.1.1.3.0',
);
get.pl (2/2)
#Program Begins
$host="163.22.20.16";
$comm="public";
($sDesc, $sOID, $sUptime)=&snmpget($host,
$comm, 'sysDescr', 'sysUptime', 'sysContact');
if ($desc == -1) {
print "Fail to access $host.\n";
}
else {
print "sysDesc: $sDesc\n";
print "sysOID: $sOID\n";
print "sysUptime: $sUptime\n";
}
exit 0;
gettable.pl (1/2)
#!/usr/local/bin/perl
require 5.003;
use SNMP_Session "0.52";
use BER "0.50";
$SNMPDEBUG=0;
$DEBUG=0;
%snmpget::OIDS =
('ipAddrTable' => '1.3.6.1.2.1.4.20',
'ipAdEntAddr' => '1.3.6.1.2.1.4.20.1.1',
'ipAdEntIfIndex' => '1.3.6.1.2.1.4.20.1.2',
'ipAdEntNetMask' => '1.3.6.1.2.1.4.20.1.3',
'ipAdEntBcastAddr' => '1.3.6.1.2.1.4.20.1.4',
'ipAdEntReasmMaxSize' => '1.3.6.1.2.1.4.20.1.5',
);
gettable.pl (2/2)
#Program Begins
$host="163.22.20.16";
$comm="public";
#@ipAddrTable=&snmpgettable($host, $comm,"ipAddrTable");
#for ($i=0;$i<=$#ipAddrTable;$i++) {
#
print "$ipAddrTable[$i]\n";
#}
@ipAddr=&snmpgettable($host, $comm, "ipAdEntAddr");
@ifIndex=&snmpgettable($host, $comm, "ipAdEntIfIndex");
@ipNetMask=&snmpgettable($host, $comm, "ipAdEntNetMask");
print "IP Address\tInterface\tSubNet Mask\n";
print "----------------------------------------------\n";
for ($i=0;$i<=$#ipAddr;$i++) {
print "$ipAddr[$i]\t$ifIndex[$i]\t$ipNetMask[$i]\n";
}
Use SNMP_util.pm in MRTG/lib
#!/usr/local/bin/perl
require 5.003;
use SNMP_util "1.04";
#Program Begins
$host="public\@163.22.20.16";
#$comm="public";
($sDesc, $sOID, $sUptime)=&snmpget($host, 'sysDescr', 'sysUptime', 'sysContact');
if ($desc == -1) {
print "Fail to access $host.\n";
}
else {
print "sysDesc: $sDesc\n";
print "sysOID: $sOID\n";
print "sysUptime: $sUptime\n";
}
exit 0;