Overview
This article will demonstrate how to execute commands on a remote server in Java using Secure iNet Factory.
Code Example
Download RLoginEx.java
01 import com.jscape.inet.bsd.*;
02 import java.io.*;
03
04 public class RLoginEx extends BsdAdapter
05 {
06 private Rlogin lg = null;
07
08 public RLoginEx(String remoteHost, String username, String localUserName, String terminalType)
09 {
10 lg = new Rlogin(remoteHost, username, localUserName, terminalType); lg.addBsdListener(this);
11 }
12
13 public void openConnection() throws BsdException
14 {
15 lg.connect();
16 }
17
18 public void closeConnection() throws BsdException
19 {
20 lg.disconnect();
21 }
22
23 public void performNegotiation() throws BsdException
24 {
25 lg.execute();
26 }
27
28 public String readData() throws BsdException, IOException
29 {
30 InputStream in = lg.getInputStream();
31 StringBuilder builder = new StringBuilder();
32 byte[] b = new byte[1024];
33 while (in.read(b) != -1) builder.append(b.toString());
34 return builder.toString();
35 }
36
37 public void writeData(byte[] data) throws BsdException, IOException
38 {
39 OutputStream st = lg.getOutputStream();
40 st.write(data);
41 }
42
43 public void connected(BsdConnectedEvent event)
44 {
45 System.out.println("Connected to host: " + event.getHostname());
46 }
47
48 public void disconnected(BsdDisconnectedEvent event)
49 {
50 System.out.println("Disconnected from host: " + event.getHostname());
51 }
52
53 public static void main(String[] args)
54 {
55 try
56 {
57 String remoteHost = null;
58 String username = null;
59 String localUserName = null;
60 String terminalType = null;
61 // create a new RLoginEx instance
62 RLoginEx ex = new RLoginEx(remoteHost, username, localUserName, terminalType);
63 // open connection to the server
64 ex.openConnection();
65 // read data
66 String data = ex.readData();
67 // write data
68 byte[] d = new byte[1024];
69 ex.writeData(d);
70 // close connection to the server
71 ex.closeConnection();
72 }
73 catch (Exception e)
74 {
75 e.printStackTrace();
76 }
77 }
78 }
Lines 1-2 : Necessary import statements. Lines 8-11 : Construct a new Rlogin instance. Lines 13-26 : Methods to connect, disconnect and execute commands. Lines 28-35 : Return response as a string. Lines 37-41 : Write data to the server. Lines 43-51 : Methods to recieve events from BsdAdapter. Line 62 : Create a new RLoginEx instance. Line 64 : Open connection. Line 66 : Read data. Lines 68-69 : Write data to the server. Line 71 : Close connection to the server.
Go here to read more details regarding rlogin.
|
Comments