December 5, 2006

Simple network scripts

Changing your network settings can be performed with either the system-config-network command or by editing the /etc/sysconfig/network-scripts/ifcfg-ethX file.

However, if you are like me, and need to change the ip address sometimes on the fly, you will not want to a simple script to perform the task instead. A simple shell script will do the job nicely. Perl or python will also do the job. I prefer writing small scripts in Perl, so here is a simple network script you can try.

Backup your resolv.conf file before running the script or add this line to your script.
The # represents a line with comments. This line is ignored by Perl when reading the code.

system("cp /etc/resolv.conf /etc/resolv.conf.org");


Let's call the script network_one.pl
The .pl stands for Perl executable.

#!/usr/bin/perl -w
# network_one.pl

system("ifconfig eth0 down");
system("ifconfig eth0 192.168.0.88 netmask 255.255.255.0");
system("route add default gw 192.168.0.1");

# Quick and dirty edit of your nameserver settings.
system("cp /etc/resolv.conf /etc/resolv.conf.org");
system("echo "nameserver 192.168.0.2 > /etc/resolv.conf");

# The echo command with the >, will overwrite your resolv.conf file.
# Check that your host can reach the default gateway. Two packets should do.
#

system("ping -c 2 192.168.0.1");

# Check that the DNS is resolving addresses.
system("dig -x somedomain");

If your dig -x somedomain executes successfully, you should be ready to network.

Next, I just copy this file and name it to network_two.pl, and edit the values for the network.

This way, you can quickly switch between numerous different networks with just calling your scripts with Perl.

# perl network_one.pl
or
# perl network_two.pl
etc ..



This is just a very simple script. A lot more sophistication can be added to the scripts of course.