0

Java newbie question,

I'm attempting to move some of my scripting from Perl based to Java and I have had good luck finding answers in examples here but this one has me stumped. I have tried without success to duplicate similar behavior to Perl script using the expect module.

$exp->spawn("ssh -l $username $dev_ip\n");
$exp->expect(15,
   [ qr/ssh -l $username $dev_ip\r/ => sub { exp_continue; } ],
   [ qr/\(yes\/no\)\?\s*$/ => sub { $exp->send("yes\n"); exp_continue; } ],
   [ qr/[Pp]assword:\s*$/ => sub {$exp->send("$password\n");exp_continue;}],
   [ qr/User/ => sub { $exp->send("$username\n"); exp_continue;} ],
   [ qr/Press any key to continue/ => sub {$exp->send("\n");exp_continue;}],
   [ qr/$prompt/i => sub { $exp->send("\n");],);

The above times out after 15 seconds if the prompt line is never reached. It also has multiple conditions it could see and respond to while trying to log in by calling sub routines.

I think based on what Ive read that I need to use interact similar to the following example, but im not totally sure what lambda does here. Could someone provide more verbose detail?

expect.interact()
    .when(contains("abc")).then(r -> System.out.println("A"))
    .when(contains("xyz")).then(r -> System.err.println("B"))
    .until(contains("exit"));
    System.out.println("DONE!");

I suspect I need an example of responding to prompts while staying in the interact loop, and perhaps wrapping the whole interact within some type of timer to provide a default action if nothing results in a log on prompt.

I have looked at

expect.expect(anyOf(contains("string"), regexp("abc.*def")));

but didn't think it would meet my needs because I don't see a way to respond to a match while continuing to look for others.

T Campion
  • 21
  • 4

1 Answers1

0

I think it is possible to replicate the functionality using interact in ExpectIt. The lambdas in the example you mentioned print some text to the standard output stream when the user types in a certain string.

You can access the 'expect' instance inside the lambda function to send commands or start a new interactive loop.

Here is how approximately the equivalent Java code could look like:

        expect.withTimeout(15, TimeUnit.SECONDS)
                .interact()
                .when(regexp("\\(yes\\/no\\)\\?\\s*$"))
                        .then(r -> expect.sendLine("yes"))
                .when(regexp("User")).then((r) -> expect.sendLine("$user"))
                .when(regexp("[Pp]assword")).then((r) -> expect.sendLine("$password"))
                .when(contains("Press any key to continue")).then((r) -> expect.sendLine())
                .until(regexp("$prompt"));

Note that in version 0.8.1 and below you have to handle a checked IOException inside the lambda function.

Alexey Gavrilov
  • 10,593
  • 2
  • 38
  • 48