Search code examples
javaexpectexpectit

Interactively entering enable mode with Java and expectit


I am doing some maintenance on some network devices and I've been using Expectit to navigate through the menus. However, I've only been successful when the devices provide prompts I expect. For example, some devices are already in enable mode when I log in, but some are not.

I would like to do the equivalent of:

Expect expect = new ExpectBuilder()
        .withOutput(channel.getOutputStream())
        .withInputs(channel.getInputStream(), channel.getExtInputStream())
        .withEchoOutput(wholeBuffer)
        .withEchoInput(wholeBuffer)
        .withExceptionOnFailure()
        .build();

channel.connect();
if (expect.expect(contains(">")) {
    expect.sendLine("enable");
    expect.expect("assword:");
    expect.sendLine(password);
}
expect.expect(contains("#"));

but I know this isn't right and it doesn't work. Some assistance on implementing a reaction to a certain prompt and another reaction to other prompts would be appreciated. Thanks!


Solution

  • You can try ExpectIt#interact but it seems to be broken in version 0.8.0, so try out the latest version 0.8.1.

    Without interact you can use the anyOf matcher and have the logic based on the condition of individual results. This is basically how interact works. Here is an example:

    MultiResult multiResult = expect.expect(anyOf(contains(">"), contains("#")));
    if (multiResult.getResults().get(0).isSuccessful()) {
        expect.sendLine("enable");
        expect.expect(contains("assword:"));
        expect.sendLine(password);
    } else if (multiResult.getResults().get(1).isSuccessful()) {
       expect.expect(contains("#"));
    }
    

    Hope it helps.