Perl:如何捕获Expect.pm的输出?

时间:2013-03-21 13:10:13

标签: perl glob

我使用Expect.pm编写了一段perl代码来生成ssh密钥。代码可以按预期创建密钥。但我不知道如何从输出中捕获指纹

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: ")) {}; # Capture the output
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;

以下是输出:

% ./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.
**The key fingerprint is:
df:aa:35:19:28:06:0e:97:ec:6d:83:26:b9:01:4f:50** my comments
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: #Expect=GLOB(0x1e74b38)#

我猜信息在Glob中?但是如何解析Glob? 谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

以下内容应该有效,或者至少应该能够将其修改为您需要的套件。 我正在等待指纹后打印的字符串“我的评论”,然后使用* exp_before *方法读取指纹。

use strict;
use Expect;

my $passwd = "abcdefg";
my $keyFile = './mykey';

my $cmd = qq/ssh-keygen -t rsa -b 2048 -C "my comments" -f $keyFile/;

my $session=Expect->spawn($cmd) or die "Error calling external program:  $!";    

my $output;        
$session->expect(10,
  [ qr/passphrase/i, sub { my $self = shift;
      $self->send("$passwd\n");
      exp_continue; }],
  [ qr/my comments/i, sub { my $self = shift;
      $output = $self->exp_before;
      exp_continue; }],
);


      print $output;

$session->soft_close;