开发者

Location of Sample Code for Java Driving Telnet at a High Level

开发者 https://www.devze.com 2023-04-04 08:08 出处:网络
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 li

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.


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);


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

See also:

  • Java - Writing An Automated Telnet Client

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:

  • How to disable echo when sending a terminal command using apache-commons-net TelnetClient
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号