ExpectJ for Telnet

684 Views Asked by At

I want to use equivalent of Expect in Java. This is a simple code:

public class TelnetJExpect
{
    @Test
    public void telnetTest() 
    {
        ExpectJ expectinator = new ExpectJ(5);
        try
        {
            Spawn shell = expectinator.spawn("172.17.80.161", 23);
            System.out.println("\nExit: " + shell.getCurrentStandardOutContents());
            shell.stop();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            assertTrue(false);
        }
    }
}

As a result, I'm getting garbage:

ÿýÿý ÿý#ÿý'

Exit:

ÿýÿý ÿý#ÿý'

However, I get connection when I use telnet from the command line.

Please help.

1

There are 1 best solutions below

0
On

try this

    ExpectJ ex = new ExpectJ(50);

    //org.apache.commons.net.telnet.TelnetClient
    TelnetClient telnetClient = new TelnetClient();
    telnetClient.connect("192.168.56.101");

    /*
     * add this constructor to TelnetSpawn
     * 
     * public TelnetSpawn(InputStream in, OutputStream out) throws IOException {
        this.m_socket = null;
        m_fromSocket = in;
        m_toSocket = out;
     */
    TelnetSpawn telnetSpawn = new TelnetSpawn(telnetClient.getInputStream(), telnetClient.getOutputStream());
    Spawn spawn = ex.spawn(telnetSpawn);
    try{
        //provide username and password here
        spawn.interact();
    }catch(NullPointerException npe){
        //ignore, nasty expectj bug
    }