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 = ;

#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 = ;

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

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

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

my @newlines2;
foreach(@lines2) {
   $_ =~ s/iface eth0 inet dhcp/iface eth0 inet $staticn address $newIPn netmask gateway;                       
print "Interface file orginal contents have been modified with new settings... n";
open(FILE2, ">$ipFile") || die "Can't open $ipFile $! n";
print FILE2 @newlines2;
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;
print "Bye !n";

You may also like


  1. Hi

    I have been looking for something like this, thanks.

    Running the script as sudo perl throws the below error unfortunately

    syntax error at /home/pi/Desktop/ line 4, near “= ;”
    syntax error at /home/pi/Desktop/ line 21, near “= ;”
    syntax error at /home/pi/Desktop/ line 38, near “= )”
    Execution of /home/pi/Desktop/ aborted due to compilation errors.

  2. You get the syntax errors because some special characters didn’t survive the upload to the site;

    $newName = ;

    should be

    $newName = ;

    the n at the end of prints should be \n etc.

  3. how ironic, I couldn’t update the characters either; it’s gobbling the less than symbol followed by the greater than symbol.

Leave a Reply

Your email address will not be published. Required fields are marked *