Tag: bash networking script
[Ubuntu/Linux] Set networking script
by Chuck Kozler on Dec.09, 2009, under Computers, Home, Linux/Unix, Networks/Servers, Ubuntu
Hi Everyone,
I have to manually change my network configuration settings a lot on my laptop when I’m at work and jumping between routers and other networks.
I got tired of manually entering all the commands so I wrote this. I expanded it a bit so other people can use it.
Its a quick and dirty script so it doesnt catch errors. Just checks if ifconfig and route commands were executed successfully.
Its pretty self explanitory. It takes in arguments of
device = the device you want to modify (eth0, eth1, etc…)
ip = the IP you want to set for yourself
gateway = The gateway you’re connecting to
dns = This is optional but you can set your own single DNS server address. If you do not enter one, the script will ask you if you want it to set you default ones with OpenDNS’ DNS server (http://opendns.org).
#!/bin/bash script_name=`basename $0` echo "" if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then echo "Usage is: " echo "" echo " $script_name [device] [ip_addr] [gateway] [Optional: one_dns_server]" echo "" echo "Note: Only one DNS server can be set. Manually update resolv.conf if you want more" echo "Note: If no DNS is specified, the script will ask you if you want it to set you one." echo "" echo "" echo "Example: " echo "" echo " $script_name eth0 192.168.1.135 192.168.1.1 4.2.2.2" echo "" exit 0 fi device="$1" ip="$2" gw="$3" primary_dns="$4" user=`echo $USER` ans='y' if [ $user != "root" ]; then echo "You must be root to run this" exit 108 fi if [ -z $device ]; then echo "You must specify a device to modify" exit 5 fi if [ -z $ip ]; then echo "You must specify an IP address for your machine" exit 5 fi if [ -z $gw ]; then echo "You must specify a default gateway address" exit 5 fi if [ -z $primary_dns ]; then echo "* No DNS server set." echo "* You do not need to specify a DNS server but it is suggested" echo "* Would you like the script to write default DNS for you (using OpenDNS)? [y/n] (default: y)" read ans echo "Write DNS = " $ans fi # Do the networking configuration # ifconfig eth0 $ip if [ $? -eq 0 ]; then success=1 fi route add default gw $gw ret="$?" if [ $ret -eq 0 ] || [ $ret -eq 7 ]; then success=2 fi if [ ! -z $primary_dns ]; then su -c "echo nameserver $primary_dns > /etc/resolv.conf" else if [ $ans == 'y' ] || [ $ans == 'Y' ]; then su -c "echo nameserver 208.67.222.222 > /etc/resolv.conf" su -c "echo nameserver 208.67.222.220 >> /etc/resolv.conf" fi fi device_ip=`ifconfig eth0 | grep -i $ip | cut -d ':' -f2 | cut -d ' ' -f1` route_gw=`route -n | grep -i 192.168.155.1 | awk '{ print $2 }'` route_flag=`route -n | grep -i 192.168.155.1 | awk '{ print $4 }'` if [ $success -eq 2 ]; then echo "" echo "* Success!" echo "" echo "* IP: $device_ip" echo "* Gateway: $route_gw ( $route_flag )" echo "" fi exit