替换ip地址脚本
1、适合FreeBSD和Linux
2、支持多IP替换
3、替换前按当前日期先做备份
4、产生日志记录,以便事后检查
复制内容到剪贴板
代码:
#!/usr/bin/perl
use strict;
#use warnings;
#
# host IP Address replace
# By zack(zack@wuhuren.com)
# LastUpadte: 2005-12-21 16:29
#
my $logfile = "my.log";
my $iplist = "iplist.txt";
my $cur_gateway = "";
my $new_gateway = "";
my $date = localtime(time);
#
# 需要修改IP地址的文件列表
# /etc/hosts
# /etc/rc.conf (for FreeBSD)
# /etc/sysconfig/network-scripts/ifcfg-eth0 (for Linux)
# /etc/virtualrec
# /var/www/conf/httpd.conf
#
my $hosts = "/etc/hosts";
my $rc = "/etc/rc.conf";
my $ifcfg = "/etc/sysconfig/network-scripts/ifcfg-eth0";
my $virtualrec = "/etc/virtualrec";
my $httpd = "/var/www/conf/httpd.conf";
my @FreeBSD_list = ($hosts,$rc,$virtualrec,$httpd);
my @Linux_list = ($hosts,$ifcfg,$virtualrec,$httpd);
my $os = `uname -s`;
chop $os;
my $hostname = `hostname -s`;
chop $hostname;
my @cur_ip;
my @new_ip;
my @farray;
my $gateway;
insert_log("start...");
insert_log("This Sever is $os.");
if ($os eq "Linux"){
@farray = @Linux_list;
$gateway = $ifcfg;
insert_log("print require change file list: @farray");
get_ip($hostname);
if ( @cur_ip != @new_ip){die insert_log(" is not match! Break!");}
}elsif ($os eq "FreeBSD"){
@farray = @FreeBSD_list;
$gateway = $rc;
get_ip($hostname);
if ( @cur_ip != @new_ip){die insert_log("is not match! Break!");}
}else{
die insert_log("Unknow System! Break!");
}
my $fcount = 1;
my $suffix = `date +%Y%m%d%H%M`; chop($suffix);
while ($fcount <= @farray){
if ( -e $farray[$fcount-1]){
insert_log("find \"$farray[$fcount-1]\" ");
insert_log("cp $farray[$fcount-1] $farray[$fcount-1].$suffix ");
`cp $farray[$fcount-1] $farray[$fcount-1].$suffix `;
my $iplistcount = 1;
while ( $iplistcount <= @new_ip) {
insert_log("perl -p -i -e 's/$cur_ip[$iplistcount-1]/$new_ip[$iplistcount-1]/g' $farray[$fcount-1]");
`perl -p -i -e 's/$cur_ip[$iplistcount-1]/$new_ip[$iplistcount-1]/g' $farray[$fcount-1] `;
$iplistcount++;
}
}else{
insert_log("cannot find \"$farray[$fcount-1]\" file!");
}
$fcount++;
}
#change gateway
insert_log("perl -p -i -e 's/$cur_gateway/$new_gateway/g' $gateway");
`perl -p -i -e 's/$cur_gateway/$new_gateway/g' $gateway `;
insert_log("end!");
sub insert_log {
open ( FHLOG, ">> $logfile" ) || open(FHLOG,"> $logfile");
flock( FHLOG, 2 );
print FHLOG "$date -> $_[0]\n";
close(FHLOG);
print "$_[0]\n";
}
#从iplist.txt文件中提取IP地址。
sub get_ip{
open(FH,$iplist) || die ("open file error!");
while (<FH>){
if (/^$hostname/){
my @iparr = split(/\s/);
push(@cur_ip,$iparr[1]);
push(@new_ip,$iparr[2]);
}
}
close(FH);
insert_log("find cur_ip: @cur_ip");
insert_log("find new_ip: @new_ip");
} [
本帖最后由 zack 于 2005-12-21 16:33 编辑 ]