2010-11-17 33 views
1

我在最後一個perl腳本上工作來更新我的/ etc/hosts文件,但我堅持並想知道是否有人可以幫忙嗎?使用perl腳本來解析文件,然後更新/ etc/hosts

我有一個IP地址的文本文件,需要讓我的Perl腳本讀取這個文件,這個文件已經完成了,但現在我更新了/ etc/hosts文件。

這裏是迄今爲止我的腳本:

#!/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"; 

然後我需要找到在/ etc中的條目/主機像

remote.host.tld 192.168.0.20

所以我知道我需要解析它爲remote.host.tld,然後替換第二位,但因爲IP不會是相同的,我不能直接替換。

任何人都可以使用的最後一位幫助請IM卡:(

三江源

+0

你是什麼意思不能直接取代?你不是用新的IP替換IP嗎?或者你沒有remote.host.tld信息或需要更換的舊IP? – 2010-11-17 19:59:20

回答

1

你的替代將是這樣的:

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

更換可以在一行來完成:

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

嗨,感謝您的迴應,愚蠢的我得到了錯誤的方式,/ etc/hosts是「192.168.1.20 host.domain.tld」而不是其他方式。另外,我將如何將替換行集成到我的腳本中,以及如何指定/ etc/hosts文件? – ard 2010-11-17 20:56:17

+0

夢幻般的謝謝! :) – ard 2010-11-17 21:27:19

+0

嗨對不起,重新打開這個,但我將如何將其整合到我現有的腳本?因爲如果我理解正確,這僅僅是一個perl內存? – ard 2010-11-18 11:41:57

0

好的,我更新了我的腳本,包括文件編輯等全部在一個。不是最好的辦法,但它的工作原理:)

#!/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