简体   繁体   中英

Java, Telnet, check for String in an InputStream

I am fairly raw. I am trying to write a Java class to interact with Telnet. I saw that Apache Commons and Jsacpe had APIs. I am using Jscape's Sinetfactory. The Telnet I am connecting to sends a prompt to enter 'User name?:' as soon as telnet.connect() occurs. I am required to verify that this prompt is actually happening so I do not just write the answer when something else may happen. I am inexperienced with this and am sure there is a simple answer, just wondering if anyone might be able to help.

Here is what I have, its a bit sloppy because I've been playing around for awhile not sure how to actually read the last characters from the stream.

import com.jscape.inet.telnet.*;

public class TelnetTest extends TelnetAdapter {

    private final static String USER = "xxx\r";
    private final static String PWORD = "yyy\r";
    private final static String COMMAND = "zzz\r";
    private final static byte[] USER_BYTE = USER.getBytes();
    private final static byte[] PWORD_BYTE = PWORD.getBytes();
    private final static byte[] COMMAND_BYTE = COMMAND.getBytes();
    private Telnet telnet = null;
    private OutputStream output = null;
    private static BufferedReader reader = null;
    private boolean connected = false;
    private String hostname = "qqq";
    //TelnetInputStream tis = null; NOT IN USE AS OF NOW

    public TelnetTest() throws IOException, TelnetException {

        // create new Telnet instance
        telnet = new Telnet(hostname);

        // register this class as TelnetListener
        telnet.addTelnetListener(this);

        // establish Telnet connection
        telnet.connect();
        connected = true;
        output = telnet.getOutputStream();

// HERE IS WHERE I NEED HELP, NOT SURE HOW TO CHECK STREAM
        String str = null;
        if ((str = reader.readline()).equals("User name?:")) {
            telnet.getOutputStream().write(USER_BYTE);
        }
// SAME CHECK WOULD HAPPEN HERE FOR "Password"
        telnet.getOutputStream().write(PWORD_BYTE);
//  ANOTHER SIMILAR CHECK HERE
        telnet.getOutputStream().write(COMMAND_BYTE);

        // sends all data entered at console to Telnet server
        String input = null;
        while ((input = reader.readLine()) != null) {
            if (connected) {
                ((TelnetOutputStream) output).println(input);
            } else {
                break;
            }
        }
    }

    public boolean streamContainsString(Reader reader, String searchString)
            throws IOException {
        Scanner streamScanner = new Scanner(reader);
        if (streamScanner.findWithinHorizon(searchString, 0) != null) {
            return true;
        } else {
            return false;
        }
    }

    // Invoked when Telnet socked is connected.
    public void connected(TelnetConnectedEvent event) {
        System.out.println("Connected");
    }

    // Invoked when Telnet socket is disconnected. Disconnect can
    public void disconnected(TelnetDisconnectedEvent event) {
        connected = false;
        System.out.print("Disconnected.  Press enter key to quit.");
    }

    // Invoked when Telnet server requests that the Telnet client begin performing               specified TelnetOption.
    public void doOption(DoOptionEvent event) {
        // refuse any options requested by Telnet server
        telnet.sendWontOption(event.getOption());
    }

    // Invoked when Telnet server offers to begin performing specified TelnetOption.
    public void willOption(WillOptionEvent event) {
        // refuse any options offered by Telnet server
        telnet.sendDontOption(event.getOption());
    }

    // Invoked when data is received from Telnet server.
    public void dataReceived(TelnetDataReceivedEvent event) {
        // print data recevied from Telnet server to console
        System.out.print(event.getData());
    }

    public Telnet getTelnet() {
        return telnet;
    }

    // starts console program
    public static void main(String[] args) {
        try {
            // create BufferedReader to read data from console
            reader = new BufferedReader(new InputStreamReader(System.in));

            // create new TelnetExample instance
            TelnetTest example = new TelnetTest();

        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    }
}

If you are reading/writing Strings then you should always use Reader and Writer . BufferedReader allows you to do line operations. So a BufferedReader wrapped around an Reader (around a InputStreamReader ) will allow you to do a readLine() call to get the line of input from the connection:

 BufferedReader reader =
     new BufferedReader(new InputStreamReader(telnet.getInputStream()));

To write to the connection you would use a Writer around a OutputStreamWriter :

 Writer writer = new OutputStreamWriter(telnet.getOutputStream()));

I'm not sure if that works with the stream from Telnet but it works with a raw Socket . You then could do something like the following pseudo code:

 while (true) {
     read a line from the server
     some sort of if/then/else to test for the output
     write your username/password or whatever is appropriate for the connection
     repeat until some logout or IOException...
 }

The Apache Telnet class has a number of interesting listeners and other handlers which you could use if you wanted to but the learning curve may be more. Here's a good sample application using TelnetClient :

http://www.java2s.com/Code/Java/Network-Protocol/ExampleofuseofTelnetClient.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM