Overview
This article will demonstrate how to communicate with telnet servers in Java using Secure iNet Factory.
Code Example
Download TelnetEx.java
01 import java.io.IOException;
02 import java.io.OutputStream;
03
04 import com.jscape.inet.telnet.*;
05 import com.jscape.inet.telnet.options.TerminalType;
06
07 public class TelnetEx extends TelnetAdapter
08 {
09 Telnet telnet = null;
10 String data = null;
11
12 public TelnetEx(String server)
13 {
14 telnet = new Telnet(server);
15 telnet.addTelnetListener(this);
16 }
17
18 public void openConnection() throws TelnetException
19 {
20 telnet.connect();
21 }
22
23 public void closeConnection() throws TelnetException
24 {
25 telnet.disconnect();
26 }
27
28 public void dataReceived(TelnetDataReceivedEvent event)
29 {
30 this.data = event.getData();
31 }
32
33 public void sendData(String command) throws IOException
34 {
35 // get OutputStream
36 OutputStream out = telnet.getOutputStream();
37 // send command to Telnet server
38 out.write(command.getBytes());
39 // write CRLF indicate end of command
40 out.write("\n".getBytes());
41 }
42
43 public void connected(TelnetConnectedEvent event)
44 {
45 System.out.println("Connected to host: " + event.getHost());
46 }
47
48 public void disconnected(TelnetDisconnectedEvent event)
49 {
50 System.out.println("Disconnected from host: " + event.getHost());
51 }
52
53 public void doOption(DoOptionEvent event)
54 {
55 TelnetOption option = event.getOption();
56 telnet.sendWillOption(option);
57 // use telnet.sendWontOption() to refuse options
58 }
59
60 public void willOption(WillOptionEvent event)
61 {
62 TelnetOption option = event.getOption();
63 telnet.sendDoOption(option);
64 // use telnet.sendDontOption() to refuse options
65 }
66
67 public void doSubOption(DoSubOptionEvent event)
68 {
69 TelnetOption option = event.getOption();
70 // check if TERMINAL-TYPE option
71 if(option.getOptionCode() == 24)
72 {
73 // create new TerminalType instance to emulate vt100 terminal
74 TerminalType tt = new TerminalType("vt100");
75 // send subnegotation data to server
76 telnet.sendOptionSubnegotiation(tt);
77 }
78 }
79
80 public static void main(String[] args)
81 {
82 try
83 {
84 TelnetEx e = new TelnetEx("telnet.myserver.com");
85 e.openConnection();
86 e.sendData("ls -al");
87 e.closeConnection();
88 }
89 catch (Exception e)
90 {
91 e.printStackTrace();
92 }
93 }
94 }
Lines 1-5 : Necessary import statements. Line 14 : Initialize Telnet instance. Line 15 : Add listener to Telnet instance so it can receive events from TelnetAdapter Lines 18-26 : Methods to open and close connections. Lines 28-31 : This method is called when data is received from the server. Lines 33-41 : Send data to the server. Lines 43-51 : Event handlers for connected and disconnected events. Lines 53-65 : Methods to accept or reject telnet options. Lines 67-78 : Perform option subnegotiation. Line 84 : Create TelnetEx instance. Line 86 : Send listing command to telnet server.
|
Comments