常用perl模块的使用

1.   Net::Ping,perl的ping模块,范例:

[pl]

#!/usr/bin/perl -w
use strict;
use Net::Ping;
sub ping_check{
my $dest=shift;
my $mp = Net::Ping->new("icmp");
if($mp->ping($dest,2)){
print "$dest is alive\n";
}else {
print "$dest is dead\n";
}

$mp->close;
}
while (my $host=<>){
chomp $host;
&ping_check($host);

} [/pl]

2.File::Copy 主要提供了copy和move函数

[pl]

#!/usr/bin/perl
use strict;
use warnings;
use File::Copy;
my $filein=$ARGV[0];
my $fileout=$ARGV[1];
copy($filein,$fileout) or die "copy $filein to $fileout failed\n";
move($fileout,"$fileout.test") or die "mv  $fileout to  $fileout.txt failed\n";

[/pl]

3.File::Rsync;

[pl]

#!/usr/bin/perl
use strict;
use warnings;
use File::Rsync;
my $filein=$ARGV[0];
my $fileout=$ARGV[1];
&rsync_file($filein,$fileout);
sub rsync_file{
my $localdir=shift;
my $remotedir=shift;
print "rsync file from $localdir to $remotedir\n";
my $obj = File::Rsync->new( { archive => 1, compress => 1 ,del=>1} );
$obj->exec( { src => $localdir, dest => $remotedir } ) or warn "rsync failed\n";

}

[/pl]

需要注意在使用rsync的时候Rsync->new里面的参数del,del表示删除目标文件中有但是源文件没有的文件。

另外就是如果我们是同步两个目录,应该使用rsync dir1/ dir2这样的形式。

如果使用sync dir1 dir2的话,结果就是dir1被放到dir2下面去了,也不要使用rsync dir1/* dir2的形式,否则当dir1是空文件夹的时候会报错。

4.  Net::OpenSSH

[pl]

#!/usr/bin/perl
use strict;
use warnings;
use Net::OpenSSH;
my $rhost=shift;
my $cmd=shift;
&remotessh_cmd($rhost,$cmd);

sub remotessh_cmd{
my $host=shift;
my $cmd=shift;
chomp $host;
my $private_key_path=’/root/.ssh/id_rsa’;
my $ruser="root";
my %opt=("user"=>$ruser,"key_path"=>$private_key_path,"timeout"=>3,"kill_ssh_on_timeout" => 1);
my $ssh= Net::OpenSSH->new($host,%opt);
$ssh->error and die "Couldn’t establish SSH connection: ". $ssh->error;
my $out=$ssh->capture($cmd);
print "SSH result:$out";
$ssh->error and die "remote command failed:".$ssh->error;
}

[/pl]

如果不是太在意执行结果的输出,可以直接使用 $ssh->system($cmd)来操作,需要注意执行返回值的问题,比如你强制杀掉某个进程,如果这个进程不存在了返回值就不是0,需要用$ssh->system(“$cmd;exit0”)这样的形式。

5.Getopt::Std

这个就不用多说了,解析参数用的。

getopts(“f:s:ul:”,\%options);

然后对$options{‘f’}等等进行判断是否存在,如果存在的话那么-f指定的参数就是$options{‘f’}。

6. Expect;

perl里面使用expect脚本也简单的,下面是用expect的签发证书的脚本中的一部分。

[pl]

my $exp = Expect->spawn ($cmd) or die "Cannot spawn : $cmd \n";
$exp->log_stdout(0);
$exp->log_file("expect.log");#记录整个文件
$exp->expect(30,
[ qr#Enter pass phrase for $choice{dir}/$choice{file}.key:#i => sub { my $exp = shift;
$exp->send("$choice{‘passwd’}\r");
exp_continue; }],

…………………….

)

[/pl]

此条目发表在Perl Script分类目录。将固定链接加入收藏夹。

发表回复