unijun 发表于 2018-8-31 12:20:47

编写perl 脚本完成文本 字符串插入工作

  因工作量太大,所以写了一个脚本完成自动化工作。工作内容是,在crontab中内容如下:
  


[*]*/1 * * * * /home/nagios/nsca/nagios_check_ping.sh 192.168.1.1 >/dev/null 2>&1
  

  现在改为
  


[*]*/1 * * * * /home/nagios/nsca/nagios_check_ping.sh 192.168.1.1 mobile >/dev/null 2>&1
  

  要完成自动插入mobile的工作,crontab 的条目太多,不可能手工去插入。所以我的代码如下:
  


[*]#!/usr/bin/perl -w
[*]
[*]use strict;
[*]
[*]my $crontab = "crontab.txt";
[*]# 保存 crontab 到 crontab.txt 中
[*]
[*]my $result= `crontab-l > $crontab`;
[*]
[*]
[*]open OUT,"> crontab2.txt" || die "Cann't open the file! $!";
[*]
[*]open IN,&quot;< $crontab&quot; || die &quot;Cann't open the file! $!&quot;;
[*]
[*]
[*]my $flag = 1;
[*]my $count;
[*]while(){
[*]      $count++;
[*]      my $line = $_;
[*]      chomp $line;
[*]      open MO,&quot;< mobile.txt&quot; || die &quot;Cann't open the file! $!&quot;;
[*]      while() {
[*]                my $ip_mobile = $_;
[*]                chomp $ip_mobile;
[*]                my @ip = split /\s+/,$ip_mobile;
[*]                if ( $line =~ /$ip/ ){
[*]                        my @temp= split /\s+/,$line;
[*]                        printOUT &quot; */1 * * * * $temp $ip_mobile >/dev/null 2>&1 \n&quot;;
[*]                        $flag = 1;
[*]                        last;
[*]                }else { $flag = 0;}
[*]      }
[*]      if($flag == 0 ){
[*]                print OUT &quot;$line \n&quot;;
[*]      }
[*]      $flag = 1;
[*]close MO;
[*]}
[*]close IN;
[*]close OUT;
  

  今天工作太累了,就不解释代码了。


页: [1]
查看完整版本: 编写perl 脚本完成文本 字符串插入工作