Simple but effective bash script [network adapters]


In some cases, where for example particular sets of commands is frequently used, really handy “tool” to simplify life can be used. I talk here about bash scripting.

What script does? To put it simple, scripts allows to write a sets of command in “specific way” that will be interpreted by shell (in this case “/bin/bash”). These scripts can perform from simple task like rm’ing temp files to really advanced stuff, only limitation here is a imagination and programing skills.

Below is my sample script that I use to manage my network connections. I wrote it because I have a need to change my network settings depending on my location or ‘particular needs’ and doing it by hand can be frustrating and simply takes too long. Script is fairly simple yet effective.What that script does is ask user to input a number corresponding to associated with it action. In my case I want to change IP and MAC address of my network adapters.

#!/bin/bash
x=1;

while [ $x -gt 0 ]
do
 clear
 echo -e "Chose IP addres:"
 echo -e "-------------------------"
 echo -e "[1]: 192.168.0.X"
 echo -e "[2]: 192.168.0.Y"
 echo -e "-------------------------"
 echo -e "[0]: my real MAC"
 echo -e "-------------------------"
 echo -e "[6]: type MAC"
 echo -e "[q]: Q U I T"

 read wyb
 
  if [ $wyb = "1" ]; then
    sudo ifconfig eth0 down
    sudo ifconfig eth0 hw ether XX:XX:XX:XX:XX:XX
    sudo ifconfig eth0 up
    sudo dhclient3 eth0
  fi
  if [ $wyb = "2" ]; then
    sudo ifconfig eth0 down
    sudo ifconfig eth0 hw ether XX:XX:XX:XX:XX:XX
    sudo ifconfig eth0 up
    sudo dhclient3 eth0    
  fi
  if [ $wyb = "6" ]; then
   echo Type MAC
   read addr
    sudo ifconfig eth0 down
    sudo ifconfig eth0 hw ether $addr
    sudo ifconfig eth0 up
    sudo dhclient3 eth0    
  fi
 
  if [ $wyb = "q" ]; then
     echo
     echo DONE!.
     echo ------------------------
     echo Current addres on eth0:
     sudo ifconfig eth0 | grep addr
     exit;
  fi
  if [ $wyb = "0" ]; then
    sudo ifconfig eth0 down
    sudo ifconfig eth0 hw ether XX:XX:XX:XX:XX:XX
    sudo ifconfig eth0 up  
  fi

done

Save it to file and make executable¬† (“chmod +x filename”). Sript prints available choices and, after user input, execute it.

This is of course sample code, and need some tweaks to suit yours needs.

MAC needs to be changed from [xx:xx:xx:xx:xx] into “yours” mac, and also IP address / netmask. Currently it works only for eth0 adapter, but can be simply adapted to any device.

I’m aware that there are ‘normal tools’ like network manager to perform these task, well maybe except MAC change, but in some cases [wifi specific tasks] you don’t want to use it, because it messes up a few things. Please keep in mind that is a ‘sample’ script, nothing fancy or advanced, so it’s more like ‘tip’ for a new people to this whole scripting thing then power users.

Tested on my Ubuntu 8.04 and Debian machines, works like a charm.

, , ,

Comments are closed.