1

I have looked at several questions here about using Java to drive a telnet session, and although I see some code down at the socket/protocol level, and a few recommendations for this or that telnet library, I don't see sample code or a pointer to sample code for driving a telnet session using one of those libraries. There's no reason why it can't be this easy:

MyTel session = new MyTel("host.myco");
session.start();
session.waitForThenType("login:", "imauser");
session.waitForThenType("Password:","secr3et");
String output = session.waitForThenType("Solaris", "tail MyFile.txt");
session.waitForThenType("%>","exit");
session.end();
// enjoy output here

So, looking for some example code that stays out of the telnet sockets and protocol, but can drive telnet sessions.

Dale
  • 5,520
  • 4
  • 43
  • 79

2 Answers2

2

Which Java Telnet or openSSH library?

http://sadun-util.sourceforge.net/telnet_library.html

The sadun code is part of a larger set of utilities. What you need are these files:

com.deltax.util (all)
org.sadun.util.tp (all)
org.sadun.util
> Cache.java
> ClassResolver.java
> OperationTimedoutException.java
> TelnetInputStream.java
> TelnetInputStreamConsumer.java
> TelnetNVTChannel.java
> Terminable.java
> UnixLoginHandler.java

That will allow you to write a program similar to the one in the question:

Socket s = new Socket("host.myco", 23);
Writer w = new OutputStreamWriter(s.getOutputStream());
UnixLoginHandler handler = new UnixLoginHandler(s);
TelnetInputStreamConsumer is = handler.doLogin("imauser","secre3t");
System.out.println(is.consumeInput(10000));
is.setConsumptionOperationsTimeout(10000);
w.write("tail MyFile.txt\r\n");w.flush();
String output = is.consumeByCriteria(new TelnetInputStreamConsumer.ContainsStringCriterium("$ "));
handler.doLogout();
System.out.println("output:\n" + output);
Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

I highly recommend using Apache Commons Net. In particular, their TelnetClient class.

See also:

I've implemented my own telnet client class that simply wraps the one provided by Apache. It's extensible and easy-to-use.

Note:

The only problem I encountered was disabling echo. For more information, see my unresolved question:

Community
  • 1
  • 1
mre
  • 43,520
  • 33
  • 120
  • 170