PERL Expect.pm
Expect.pm 模块:主要用来和另外一个server进行交互的,比如ftp,telnet等等。在写一些监控脚步上,也会经常用到。
我所用到的方法很简单,
spawn($command,@params),Forks and execs $command. Returns an Expect object upon success or undef if the fork was unsuccessful or the command could not be found. spawn() passes its parameters unchanged to Perls exec(), so look there for detailed semantics。起了一个新进程用来执行$command命令
new expect()->expect($timeout,$content),Given $timeout in seconds Expect will wait for $object's handle to produce one of the match_patterns, which are matched exactly by default. If you want a regexp match, prefix the pattern with '-re'.在$timeout内,期待出现包含$content的内容,默认是精确匹配,也可以使用正则表达式,expect($timeout,re =>'')
new expect()->send($string):Sends the given strings to the spawned command. 发送消息
new expect()->debug(0|1|2): 打印debug 信息,不同的数字表示不同的bug级别
new expect()->interact(),和用户进行交互,把控制权转交给用户
new expect()->soft_close(), 软关闭,直到$timeout时间到达,才关掉该进程
new expect()->hard_close(),硬关闭,立刻关闭该进程
new expect()->match(),returns the string matched by the last expect() call, undef if no string was matched.返回匹配的结果
new expect()->match_number(),exp_match_number() returns the number of the pattern matched by the last expect() call. Keep in mind that the first pattern in a list of patterns is 1, not 0. Returns undef if no pattern was matched.返回匹配的个数
例子:
#!/usr/bin/perl
use Expect;
use strict;
my $timeout = 20;
my $cmd = "telnet";
my $exp = Expect->spawn($cmd,"192.168.0.1") or die "Can't spawn $cmd!";
$exp->expect($timeout,-re=>'[Ll]ogin:');
$exp->send("test/r/n");
$exp->expect($timeout,-re=>'[Pp]assword:');
$exp->debug(1);
$exp->send("test/r/n");
$exp->expect($timeout,-re=>'Last login');
$exp->send("ps -ef |grep java/r/n");
$exp->expect($timeout,-re=>'java');
print $exp->match_number();
$exp->soft_close();
PERL Expect
最新推荐文章于 2022-11-13 12:31:00 发布