Perl Script to Modify Hostname and IP

I have taken on Perl scripting as a directed study. One of the projects going on at work is to take our 32 RaspberryPi’s and turn them into a “super computer” of sorts. We have the master and node images captured, but I have been working on a script that we can run to modify the hostnames and IP addresses of all the nodes post-imaging.

Below is my script which accepts user input for the Hostname and IP.

# This needs to be run with sudo
#
print "Please enter the new hostname: n";
$newName = ;
chomp($newName);

#Attempt to edit the hostname file
$hostFile = "/etc/hostname";

open (FILE1, ">$hostFile") or die "Can't open $hostFile: $! n"; 
print FILE1 "$newNamen";
close FILE1;

print "Hostname file has been modified! n";

#Edit the hosts file and replaces the hostname

$hostsFile = "/etc/hosts";

open(FILE, "<$hostsFile") || die "Can't open $hostsFile: $! n";
my @lines = ;
close(FILE);

my @newlines;
foreach(@lines) {
   $_ =~ s/NodePi01/$newName/g;                       
   push(@newlines,$_);
}
print "Hosts orginal contents have been modified with new Hostname... n";
open(FILE2, ">$hostsFile") || die "Can't open $! n";
print FILE2 @newlines;
close(FILE2);
print "Hosts file has been successfully modified! n";

#Does the IP configuration....
print "Please enter the new IP Address: n";
$newIP = ;
chomp($newIP);
$dhcp = "dchp";
$static = "static";
$ipFile = "/etc/network/interfaces";

open(IP, "<$ipFile") || die "Can't open $ipFile: $! n";
my @lines2 = ;
close(IP);

my @newlines2;
foreach(@lines2) {
   $_ =~ s/iface eth0 inet dhcp/iface eth0 inet $staticn address $newIPn netmask 255.255.255.0n gateway 192.168.0.1n/g;                       
   push(@newlines2,$_);
}
print "Interface file orginal contents have been modified with new settings... n";
open(FILE2, ">$ipFile") || die "Can't open $ipFile $! n";
print FILE2 @newlines2;
close(FILE2);
print "IP Address and network settings have been successfully modified! n";

#Code to reboot the node 
$reboot = '/sbin/init 6';
print "You must reboot to apply changes, do you want to reboot now? (yes/no)n";
chomp($input = );

if($input eq "yes") {
print "Now rebooting ....n";
system $reboot;
	}
else{
print "Bye !n";
}
Continue Reading