Search code examples
perlexpect.pm

Automate and capture login prompt through perl's expect


I'm trying to automate a login prompt in Perl

I'm using SSHGetCredentials('login_prompt' => 1) to generate a login prompt which is a function of perl's Expect::SSH library

This is how my code looks like, here REST::Client->getCredentials() internally calls SSHGetCredentials('login_prompt' => 1) which would call a login prompt and return the entered userID and password.

use Expect;
my $command = "perl -e 'use REST::Client; REST::Client->getCredentials()'";
my $exp = Expect->spawn($command) || die "i am done";
$exp->expect(undef, 'Login on Remote:');
$exp->send("user\n");
$exp->expect(undef, 'Password of user:');
$exp->send("12345\n");

Now I want to verify whether user name or password is what I have passed, so I want to capture them and compare.

How can I capture them?

I tried this:

use Expect;
my $command = "perl -e 'use REST::Client; \$tmp = REST::Client->getCredentials();print \$tmp->{'username'};print \" \";print \$tmp->{'password'};'";
my $exp = Expect->spawn($command) || die "i am done";
$exp->expect(undef, 'Login on Remote:');
$exp->send("user\n");
$exp->expect(undef, 'Password of user:');
$exp->send("12345\n");
my $value = $exp->expect(1);

but $value has nothing and $exp->expect(1) just prints the values in STDOUT.


Solution

  • Not sure if it's the best way but it works

    use Expect;
    my $command = "perl -e 'use REST::Client; \$tmp = REST::Client->getCredentials();print \$tmp->{'username'};print \" \";print \$tmp->{'password'};'";
    my $exp = Expect->spawn($command) || die "i am done";
    $exp->expect(undef, 'Login on Remote:');
    $exp->send("user\n");
    $exp->expect(undef, 'Password of user:');
    $exp->send("12345\n");
    if ($exp->expect(undef,'-re','user 12345') == 1) {
        print "matched\n";
    }