cjcmay 发表于 2017-5-17 10:41:16

一些perl脚本

一、常用工具方法
1、哈希
my %hash = ("a"=>1, "b"=>2, "c"=>3, "d"=>4);
foreach my $key (sort keys %hash)
{
my $value =$hash{$key};
    print "$key=$value\n";
}
2、读文件
sub readFile(){
my $line;
my $username;
my $password;
open FH, "new("icmp");
my $a=0;
my $c=0;
my $count;
foreach $b (78..100){
my $ip="192.168.81.".$b;
      if ($pinghost->ping($ip)){
         print "$ip Connected!.\n";
         $a++;
      }
      else {
         print "$ip Disconnected.\n";
         $c++;
         }   
      }
       $count=$a+$c;
       print "一共$count台计算机,$a台联通,$c台断开!";
       $pinghost->close();
}
testConnection();
4、telnet远程登录并执行操作
sub testTelnet(){

   my $hostname=$_;
   my $usename=$_;
   my $password=$_;
   my $command=$_;
   my $timeout=90,
   
   my $telnet=Net::Telnet->new(Timeout=>10,Prompt="hello");
   $telnet->open($hostname);
   $telnet->login($usename,$password);

   my @result=$telnet->cmd("$command");
   print @result;
   $telnet->close;
}
testTelnet('127.0.0.1','AT','123456','rubyD:/filefield_test.rb');
5、测试http
sub testHttp(){
my $user_agent = new LWP::UserAgent;
    my $request = new HTTP::Request('GET','http://www.163.com');
    my $response = $user_agent->request($request);
    open FILEHANDLE, ">E:/result.txt";
    print FILEHANDLE $response->{_content};
    close FILEHANDLE;
}
testHttp();
6、发email
sub testMail(){
    my $mailhost = "smtp.163.com";
    my $mailfrom =$_;
    my @mailto =$_;
    my $subject = 'Test:';
    my $text = 'E:/patch.txt';
    open(FILE,$text) || die "can't open file";
    undef $/;
    $text=<file>;
    my $smtp = Net::SMTP->new($mailhost,Hello=gt;'localhost',Timeout=gt;120,Debug =gt;1);
    $smtp->auth('user','pass');
    foreach my $mailto (@mailto) {
    $smtp->mail($mailfrom);
    $smtp->to($mailto);
    $smtp->data();
    $smtp->datasend("To:$mailto");
    $smtp->datasend("From:$mailfrom");
    $smtp->datasend("Subject:$subject");
    $smtp->datasend("");
    $smtp->datasend("$text");
    $smtp->dataend();
   }
    $smtp->quit;
}
testMail('sambafeng@163.com','sambafeng@163.com')
7、利用ftp上传文件
sub testFtp(){
my $ftpServer=$_;
my $username=$_;
my $password=$_;
my @path=$_;
my @filename=$_;
    my $ftp = Net::FTP->new("$ftpServer", Passive =gt; 0)
      or die "Cannot connect to some.host.name: $@";
    $ftp->login("$username",'$password')
      or die "Cannot login ", $ftp->message;
    $ftp->cwd("@path")
      or die "Cannot change working directory ", $ftp->message;
    $ftp->get("@filename")
      or die "get failed ", $ftp->message;
#    $ftp->put("@filename")
#      or die "get failed ", $ftp->message;
    $ftp->quit;
}
testFtp("127.0.0.1","sambafeng","123456","E:/","test.txt");</file>
8、for循环和字符串操作
my @array = (1, 2, 3, 4);
my %i;
print my $scalar = $array;
$i{$_}++ for @array;
for (@array) {
    print if $i{$_}
页: [1]
查看完整版本: 一些perl脚本