Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How capture the outputs of Expect.pm?

Status
Not open for further replies.

whn

Programmer
Oct 14, 2007
265
US
I wrote a piece of perl code to generating ssh keys using Expect.pm. The code can create keys as expected. But I don't know how to capture the finger prints from the output.

Code:
use Expect;

my $passwd = "abcdefg";
my $keyFile = './mykey';
my $cmd = qq/ssh-keygen -t rsa -b 2048 -C "my comments" -f $keyFile/;
print "\nCMD: $cmd\n\n";
my @output;
my $session=Expect->spawn($cmd) or die "Error calling external program:  $!\n";
unless ($session->expect(5,"Enter passphrase \(empty for no passphrase\): ")) {};
print $session "$passwd\r";
unless (@output = $session->expect(5,"Enter same passphrase again: ")) {}; # [b][COLOR=#EF2929]Capture the output[/color][/b]
print $session "$passwd\r";
$session->soft_close();
my $i = 1;
foreach my $e (@output) {
  if($e) {
    print "\$i = $i, Type of \$e: #". ref($e) . "#, Value of \$e: #$e#\n";
  }
  else {
    print "$i, NULL Element!\n";
  }
  $i++;
}
exit;

Here is the output:
Code:
./test.pl

CMD: ssh-keygen -t rsa -b 2048 -C "my comments" -f ./mykey
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in ./mykey.
Your public key has been saved in ./mykey.pub.
[b]The key fingerprint is:
[COLOR=#EF2929]df:aa:35:19:28:06:0e:97:ec:6d:83:26:b9:01:4f:50[/color] my comments[/b]
The key's randomart image is:
+--[ RSA 2048]----+
|..E              |
| . . .           |
|. o =            |
| + * +   .       |
|  = = * S .      |
|   = o o . +     |
|  .       = .    |
|         . o     |
|        ...      |
+-----------------+
$i = 1, Type of $e: ##, Value of $e: #1#
2, NULL Element!
$i = 3, Type of $e: ##, Value of $e: #Enter same passphrase again: #
$i = 4, Type of $e: ##, Value of $e: #
#
5, NULL Element!
$i = 6, Type of $e: #Expect#, Value of $e: #[b][COLOR=#A40000]Expect=GLOB(0x1e74b38)[/color][/b]#

I guess the info is in the Glob? But how to parse the Glob?

Thanks for the help.

 
I got the solution. Hope it helps.

Perl:
my $output;
  my $session=Expect->spawn($cmd) or die "Error calling external program:  $!\n";
  $session->expect(10,
    [ qr/passphrase/i, sub { my $self = shift;
        $self->send("$passwd\n");
        exp_continue; }],
    [ qr/$comments/i, sub { my $self = shift;
        $output = $self->exp_before;
        exp_continue; }],
  );
  print $output;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top