Saturday, December 20, 2008

Telnet client with java...

Telnet is very important utiliy we use.We can call remote server commands and use different services running on perticular port.Mostly telnet server runs on 23,but can be differed .

Through java, if we want to make remote connection over some port then we have two different ways.

1. Use windows/linux telnet command line utility (which is same on both win and linux... :).)

OR

2. Use socket programming using java.net package.

In first way, we need to get hands on the process.We can achieve that using
Process p = Runtime.getRuntime().exec(<system command or exe path>)
But i don't think this should be used for telnet like communication,because telnet requires continuous session running on remote server and executing you commands.Sometimes it can be so that after executing several commands,you need to rollback so you can cancle all the commands.so its a continuous and sequential process most of the times.The Process class used can be out of our hands anytime if the executable crashes or if anything bad happen(Mostly..the exe crash...).


So, we have another,'Socket' way here, which connects to perticular host on given port number and try to open TCP connection with it.If the host is listening on port and connection accepted,then we can send our commands to the host.(I know, i know, that we all know sockets since our starting graduation days :) ,but let me tell guys... ).

There are two ways to make a telnet client using Sockets.
1.Make it CLI based,means which accepts every input from Command Line Interface entered by user.
2.Make it automated,which takes command list from some file or database,generates a script or list of commands and run it whole on host.

First one is quite easy,i think you all might have done that :).Just let me tell you little what to do...

1.CLI based Telnet...
Socket soc = new Socket(host,port);
DataInputStream din=new DataInputStream(soc.getInputStream());
PrintWriter dout = new PrintWriter(soc.getOutputStream(),true);

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
See,we have taken InputStream of socket and made a PrintWriter on the OutputStreamof it to send commands.Also we have taken BufferedReader for user inputs from CL.

...
....

do
{
char[] buffer = new char[8192];
int mark = bReader.read(buffer);
StringBuffer sb = null;
for(int i=0;i<buffer.length;i++){
char c = buffer[i];
if(c!='\0'){ //To avoid null characters printed...
if(sb == null){
sb = new StringBuffer(buffer.length);
}
sb.append(c);
}
}
System.out.print((sb!=null)?sb.toString():"-- No Response --");
Command=br.readLine(); //takes commands from CL by user...
if(!Command.equals("quit"))
{
dout.println(Command);
}
}while(!Command.equals("quit")); //exit the loop if user sends 'quit'...
...


This gives you same telnet as you got in your OS, so i think its simple but good to know :)


2.Automated Telnet...

It will be almost same,except we will have a ArrayList/Array of commands in hand before we create Socket.And then change the loop onto the list to execute all the commands one after another...

int j=-1;
String[] commands = new String[5];

...
....

do
{
j++;
char[] buffer = new char[8192];
int mark = bReader.read(buffer);
StringBuffer sb = null;
for(int i=0;i<buffer.length;i++){
char c = buffer[i];
if(c!='\0'){//To avoid null characters printed...
if(sb == null){
sb = new StringBuffer(buffer.length);
}
sb.append(c);
}
}
System.out.print((sb!=null)?sb.toString():"-- No Response --");
Command = commands[j];
if(Command==null || Command.length()<0)
break;
dout.println(Command+"\n");
}while(j<commands.length);
...

So this will executes all commands in commands Array of String.


So folks,this ends our telnet socket :).Same like this we can make client or scripts for FTP automation.It helps in real time situation when you need to make some jobs for backup,export/import files on remote host etc...Waiting for you responses...

Wednesday, December 17, 2008

Snmp4J - Java library for SNMP Communication...

We all know that if we need to use more on socket programming in java then we must use native code in c++.SNMP (Simple network Management Protocol) is used for communication with the network devices.Any network device can be queried using SNMP request.Snmp4j is the library which provides you implementation to make SNMP requests.

We can query any device (Switch,PC etc...) if it has a SNMP agent running,which will handle our SNMP request and respond with the proper data.This library made it so easy for us without looking into much details of SNMP.

In basic,SNMP is used for getting information (GET requests),but sometimes it can be used to set values in the device (SET requests).Assume that every device has a list of pre-defined variables in it,which are called OID(Object IDs).These OIDs will have a specific structure (which is called MIB file,which seems like a tree structured as in registry).

OID looks like 1.3.6.1.4.1.318.1.1.1.12.3.2.1.3.1, which has a special meaning.It has a description(name) and an associated value in it.When you query particular OID (i.e 1.3.6.1....),it will give its associated value.You can set its value also (if its allowed ;)).OIDs also have communities(Public,Private etc...) which shows permissions.Mostly public community is allowed to be viewed by SNMP requests.

See the example below how to make a SNMP request,
import org.snmp4j.*;

...
...

OctetString communityName = new OctetString("public");

String ipAddressUrl = strIpAddress+"/"+161; //161 is used for SNMP Agent...

Address targetAddress = new UdpAddress(ipAddressUrl);

TransportMapping transport = new DefaultUdpTransportMapping();

Snmp snmp = new Snmp(transport);

snmp.listen();

CommunityTarget target = new CommunityTarget();

target.setAddress(targetAddress);
target.setRetries(3);
target.setTimeout(500);

PDU pdu = new PDU();
pdu.setType(PDU.GET);

OID oid = new OID("1.3.6.1.2.1.1.");
VariableBinding vb = new VariableBinding(oid);

pdu.add(vb);
...
...

snmp.send(pdu, target);
So the last line, snmp.send(pdu, target), will return the SNMP4j Response having the value for OID we set in the PDU.This is just the example of how to get any data from OID.We can set the values using SET PDU.