Friday, February 19, 2010

Generate hosts file with Perl

A sweet way to add couple of servers to your hosts file/NIS map using a tiny perl script:

#!/usr/bin/perl -w

use strict;
use warnings;
print `clear`;
my $j=10;

open (HOSTS ,">>/etc/hosts.txt") or die $!;
for (my $num=0;$num <= 10; $num++) {
printf(HOSTS "server$j \t server$j.domain.org \t 192.168.0.$num\n");
$j++;
}
close (HOSTS) or die $! ;

#END


The output will be:

server10 server10.domain.org 192.168.0.0

server11 server11.domain.org 192.168.0.1
server12 server12.domain.org 192.168.0.2
server13 server13.domain.org 192.168.0.3
server14 server14.domain.org 192.168.0.4
server15 server15.domain.org 192.168.0.5
server16 server16.domain.org 192.168.0.6
server17 server17.domain.org 192.168.0.7
server18 server18.domain.org 192.168.0.8
server19 server19.domain.org 192.168.0.9
server20 server20.domain.org 192.168.0.10

1 comment:

shemsu said...

This would look a little bit nicer:

use strict;
use warnings;

my $num = 10;
my $start = 10;

system("clear");
open(HOSTS , ">>/etc/hosts.txt") or die "couldn't open hosts.txt file: $!";

for (0 .. $num) {
my $id = $start + $_;
printf(HOSTS "server$id \t server$id.domain.org \t 192.168.0.$_\n");
}

close(HOSTS) or die "couldn't close hosts.txt file: $!";