开发者

Use a perl script to parse a file then update /etc/hosts

Im working on one last perl script to update my /etc/hosts file, but am stuck and wondered if someone can help please?

I have a text file with an IP in it, and need to have my perl script read this, which iv done, but now im stuck on updating the /etc/hosts file.

here is my script so far:

#!/usr/bin/perl

use strict;
my $ip_to_update;

开发者_如何学运维$ip_to_update = `cat /web_root/ip_update/ip_update.txt | awk {'print \$5'}` ;

print "ip = $ip_to_update";

I then need to find an entry in /etc/hosts like

remote.host.tld 192.168.0.20

so i know i need to parse it for remote.host.tld and then replace the second bit, but because the ip wont be the same i cant just do a straight replace.

Can anyone help with the last bit please as im stuck :(

Thankyou!


Your substitution will look like this:

s#^.*\s(remote\.host\.tld)\s*$#$ip_to_update\t$1#

Replacement can be done in one line:

perl -i -wpe "BEGIN{$ip=`awk {'print \$5'} /web_root/ip_update/ip_update.txt`} s#^.*\s(remote\.host\.tld)\s*$#$ip\t$1#"'


Ok, I updated my script to include the file edit etc all in one. Might not be the best way to do it, but it works :)

#!/usr/bin/perl

use strict;
use File::Copy;
my $ip_to_update;           # IP from file
my $fh_r;                  # File handler for reading
my $fh_w;                  # File handler for writing
my $file_read = "/etc/hosts";       # File to read in
my $file_write = "/etc/hosts.new";  # File to write out
my $file_backup = "/etc/hosts.bak"; # File to copy original to

# Awks the IP from text file
$ip_to_update = `/bin/awk < /web_root/ip_update/ip_update.txt {'print \$5'}` ;

# Open File Handlers
open( $fh_r, '<', $file_read ) or die "Can't open $file_read: $!";
open( $fh_w, '>', $file_write ) or die "Can't open $file_write: $!";

while ( my $line = <$fh_r> )
{
        if ( $line =~ /remote.host.tld/ ) 
    {
                #print $fh_w "# $line";
        }
    else
    {
        print $fh_w "$line";
    }
    }

chomp($ip_to_update);           # Remove newlines
print $fh_w "$ip_to_update          remote.host.tld\n";
        # Prints out new line with new ip and hostname

# Close file handers
close $fh_r;
    close $fh_w;

move("$file_read","$file_backup");  # Moves original file to .bak
move("$file_write","$file_read");   # Moves new file to original file loaction
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜