Overview
This article will demonstrate how to script communications with telnet servers in Java using Secure iNet Factory.
Code Example
Download TelnetScriptEx.java
01 import com.jscape.inet.telnet.*;
02
03 public class TelnetScriptEx
04 {
05 public static void main(String[] args)
06 {
07 try
08 {
09 String loginPrompt = "login:";
10 String passwordPrompt = "Password:";
11 String shellPrompt = "#";
12 String username = "jsmith";
13 String password = "secret";
14 String command = "ls –al";
15
16 // create new Telnet instance
17 Telnet telnet = new Telnet("10.0.0.1");
18 // create new TelnetScript instance and bind to Telnet instance
19 TelnetScript script = new TelnetScript(telnet);
20 // build task to submit username using regular expressions
21 TelnetTask loginTask = new TelnetTask("[Ll]ogin:","jsmith","[Pp]assword:");
22 loginTask.setStartPromptRegex(true);
23 loginTask.setEndPromptRegex(true);
24 // build task to submit password
25 TelnetTask passwordTask = new TelnetTask(passwordPrompt,password,shellPrompt);
26 // build task to execute command
27 TelnetTask commandTask = new TelnetTask(shellPrompt,command,shellPrompt);
28 // add all tasks to script
29 script.addTask(loginTask);
30 script.addTask(passwordTask);
31 script.addTask(commandTask);
32
33 // connect to telnet server … script is executed automatically
34 telnet.connect();
35 // wait until last task is complete
36 while(!commandTask.isComplete())
37 {
38 Thread.sleep(500);
39 }
40 // get response of completed task
41 String response = commandTask.getResponse();
42 // last task completed … disconnect from server
43 telnet.disconnect();
44 }
45 catch (Exception e)
46 {
47 e.printStackTrace();
48 }
49 }
50 }
Line 1 : Necessary import statement. Line 17 : Create Telnet instance. Lines 19-27 : Create TelnetTask instances. Lines 29-31 : Add TelnetTask instances to TelnetScript instance. Line 34 : Open connection to the server. Lines 36-39 : Wait for TelnetTask instance to complete. Line 41 : Read response.
|
Comments