home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: Java / Java.zip / telnet4j.zip / TelnetWrapper.java < prev    next >
Text File  |  1997-03-14  |  7KB  |  248 lines

  1. import java.io.IOException;
  2. import socket.TelnetIO;
  3.  
  4. /** Wrapper for a Java Telnet call. 
  5.  * Supports remote commands.
  6.  * Uses code from Matthias L. Jugel's and Marcus Mei▀ner's freeware
  7.  * <a href="http://www.first.gmd.de/persons/leo/java/Telnet">Telnet Applet</a>.
  8.  * Note - their Applet is under GNU copyleft, so any commercial use of
  9.  * this code is restricted. See their above site for details.
  10.  * @author George Ruban 3/4/97
  11.  * @see socket.TelnetIO
  12.  */
  13. public class TelnetWrapper
  14. {
  15.   /** The telnet connection. That which is wrapped. */
  16.   private protected TelnetIO tio;
  17.   /** Set to true for System.out.println debugging. */
  18.   private final static boolean debug = false;
  19.   /** The current prompt on the remote system. */
  20.   private String prompt;
  21.  
  22.   /** The default prompt used by all TelnetWrappers unless specifically
  23.    * overridden.
  24.    * @see #setPrompt
  25.    */
  26.   private static String defaultPrompt = "$ ";
  27.  
  28.   /** The default login name used by TelnetWrappers.
  29.    * If defaultLogin and defaultPassword are both non-null
  30.    * when a TelnetWrapper is created, the TelnetWrapper will attempt
  31.    * to login.
  32.    */
  33.   private static String defaultLogin = null;
  34.  
  35.   /** The default password used by TelnetWrappers.
  36.    * If defaultLogin and defaultPassword are both non-null
  37.    * when a TelnetWrapper is created, the TelnetWrapper will attempt
  38.    * to login.
  39.    */
  40.   private static String defaultPassword = null;
  41.   
  42.  
  43.   /** Skip any received data until the token appears. */
  44.   public void wait(String token) throws IOException
  45.   {
  46.     if(debug) System.out.println("wait(" + token + ")...");
  47.     String tmp;
  48.     do {
  49.       tmp = receive();
  50.     } while(tmp.indexOf(token) == -1);
  51.     if(debug) System.out.println("wait(" + token + ") successful.");
  52.   }
  53.  
  54.   /** Returns bytes available to be read.  Since they haven't been
  55.    * negotiated over, this could be misleading...
  56.    * -- removed because available is not in TelnetIO
  57.   public int available() throws IOException
  58.   {
  59.     return tio.available();
  60.   } */
  61.     
  62.   /** Returns a String from the telnet connection. Blocks
  63.    * until one is available. No guarantees that the string is in
  64.    * any way complete.
  65.    * NOTE: uses Java 1.0.2 style String-bytes conversion.*/
  66.   public String receive() throws IOException
  67.   {
  68.     String s = new String(receiveBytes(), 0);
  69.     if(debug) System.out.println(s);
  70.     return s;
  71.   }
  72.  
  73.   /** Returns a byte array. Blocks until data is available. */
  74.   public byte[] receiveBytes() throws IOException
  75.   {
  76.     return tio.receive();
  77.   }
  78.  
  79.   /** Returns all data received up until a certain token. */
  80.   public String receiveUntil(String token) throws IOException
  81.   {
  82.     String s = new String();
  83.     do
  84.     {
  85.       s += receive();
  86.     } while(s.indexOf(token) == -1);
  87.     return s;
  88.   }
  89.   
  90.   /** Sends a String to the remote host.
  91.    * NOTE: uses Java 1.0.2 style String-bytes conversion.
  92.    */
  93.   public void send(String s) throws IOException
  94.   {
  95.     if(debug) System.out.println(s);
  96.     byte[] buf = new byte[s.length()];
  97.     s.getBytes(0, s.length(), buf, 0);
  98.     tio.send(buf);
  99.   }
  100.  
  101.   /** Sends a line to the remote host, returns all data before the prompt.
  102.    * Since telnet seems to rely on carriage returns ('\r'), 
  103.    * one will be appended to the sent string, if necessary.
  104.    * @param command command line to send
  105.    * @return whatever data the command produced before the prompt.
  106.    * @see #setPrompt
  107.    */
  108.   public String sendLine(String command) throws IOException
  109.   {
  110.     if(command.charAt(command.length() -1) != '\r') 
  111.       command += "\r";
  112.     send(command);
  113.     String s = receiveUntil(prompt);
  114.  
  115.     // telnet typically echoes the command with a \r\n ending...
  116.     return s.substring(command.length() + 1, s.indexOf(prompt));
  117.   }
  118.   
  119.   /** Sends bytes over the telnet connection. */
  120.   public void send(byte[] buf) throws IOException
  121.   {
  122.     tio.send(buf);
  123.   }
  124.   
  125.   /** Logs in as a particular user and password. 
  126.     * Returns after receiving prompt. */
  127.   public void login(String loginName, String password) throws IOException
  128.   {
  129.     wait("login:");
  130.     send(loginName + "\r");
  131.     wait("Password:");
  132.     sendLine(password + "\r");
  133.   }
  134.     
  135.   /** Connects to the default telnet port on the given host. */
  136.   public TelnetWrapper(String host) throws IOException
  137.   {
  138.     tio = new TelnetIO();
  139.     setPrompt(defaultPrompt);
  140.     tio.connect(host);
  141.     if(defaultLogin != null && defaultPassword != null)
  142.     {
  143.       login(defaultLogin, defaultPassword);
  144.     }
  145.   }
  146.   
  147.   /** Sets the expected prompt. 
  148.    * If this function is not explicitly called, the default prompt is used.
  149.    * @see #setDefaultPrompt
  150.    */
  151.   public void setPrompt(String prompt)
  152.   {
  153.     if(prompt == null) throw new IllegalArgumentException("null prompt.");
  154.     this.prompt = prompt;
  155.   }
  156.  
  157.   /** Sets the default prompt used by all TelnetWrappers.
  158.    * This can be specifically overridden for a specific instance.
  159.    * The default prompt starts out as "$ " until this function is called.
  160.    * @see #setPrompt
  161.    */
  162.   public static void setDefaultPrompt(String prompt)
  163.   {
  164.     if(prompt == null) throw new IllegalArgumentException("null prompt.");
  165.     defaultPrompt = prompt;
  166.   }
  167.  
  168.   /** Sets the default login used by TelnetWrappers.
  169.    * If this method is called with non-null login and password,
  170.    * all TelnetWrappers will attempt to login when first created.
  171.    * @param login login name to use
  172.    * @param password password to use
  173.    * @see #login
  174.    * @see #unsetLogin
  175.    */
  176.   public static void setLogin(String login, String password)
  177.   {
  178.     if(login == null || password == null)
  179.       throw new IllegalArgumentException("null login or password.");
  180.     defaultLogin = login;
  181.     defaultPassword = password;
  182.   }
  183.  
  184.  
  185.   /** Turns off the default login of TelnetWrappers.
  186.    * After this method is called, TelnetWrappers will not
  187.    * login until that method is explicitly called.
  188.    * @see #setLogin
  189.    * @see #login
  190.    */
  191.   public static void unsetLogin()
  192.   {
  193.     defaultLogin = defaultPassword = null;
  194.   }
  195.   
  196.   /** Ends the telnet connection. */
  197.   public void disconnect() throws IOException
  198.   {
  199.     if(tio != null) tio.disconnect();
  200.     tio = null;
  201.   }
  202.   
  203.   /** Ends the telnet connection. */
  204.   public void finalize()
  205.   {
  206.     try
  207.     {
  208.       disconnect();
  209.     }
  210.     catch(IOException e)
  211.     {} // after all, what can be done at this point?
  212.   }  
  213.  
  214.   /** Telnet test driver.
  215.    * Modeled after the IOtest.java example in the Telnet Applet.
  216.    * Logs in to stems, creates a timestamped file in /tmp, lists the
  217.    * /tmp directory to System.out, disconnects.  Shows off several
  218.    * TelnetWrapper methods.
  219.    */
  220.   public static void main(String args[]) throws IOException
  221.   {
  222.     java.util.Date now = new java.util.Date();
  223.     String timestamp = now.getYear() + "-" +
  224.         (now.getMonth()+1) + "-" + now.getDate() + "-" +
  225.           now.getHours() + ":" + now.getMinutes() + ":" +
  226.             now.getSeconds();
  227.     TelnetWrapper telnet = new TelnetWrapper("someHost"); 
  228.     
  229.     // setting the correct prompt ahead of time is very important 
  230.     // if you want to use login and sendLine
  231.     telnet.setPrompt("$ ");
  232.     telnet.login("myLoginName", "myPassword");
  233.  
  234.     // this is how you have to do it otherwise
  235.     telnet.send("touch /tmp/TELNET_WRAPPER-" + timestamp + "\r");
  236.     telnet.wait("$ ");
  237.  
  238.     // sendLine 1: adds the \r automatically, 2: waits for the prompt
  239.     // before returning 3: returns what was printed from the command
  240.     String ls = telnet.sendLine("ls /tmp");
  241.     System.out.println(ls);
  242.  
  243.     // clean up
  244.     telnet.disconnect();
  245.  
  246.   }
  247. }
  248.