我编写了一段perl代码来使用Expect.pm生成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呢?谢谢你的帮助。
发布于 2013-03-22 09:50:51
以下内容应该有效,或者至少您应该能够将其修改为您需要的套件。我正在等待字符串“我的评论”,它是打印在指纹之后,然后使用*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;https://stackoverflow.com/questions/15548535
复制相似问题