Category: Shell scripting

Shell Scripting

Create Users And Change Passwords With A Bash Script

Create Users And Change Passwords With A Bash Script

Hi All,

These two scripts are very important for the system admin who regularly works with mail servers and somehow forgets to backup his system username and password! Let’s say somehow we lost the usernames and passwords of the mail server. In this case the admin has to manually create all the users and then change the passwords for all the users. Tedious job. Let’s make our life easier.

First create a file which contains all the user name. Something like this:

root@indiangnu.org:/home/arun# vi userlist.txt

Arun

Ravi

Nishikant

Ali

Nishit

Ameya

Yogesh

Santosh

Save the file as userlist.txt. Now create the following bash file:

root@indiangnu.org:/home/arun# vi useradd

#!/bin/sh

# This script is useful for adding user

for i in `more userlist.txt`

do

echo $i

adduser $i

done

Save the file and exit.

root@indiangnu.org:/home/arun# chmod 755 userlist.txt useradd

Now run the file :

root@indiangnu.org:/home/arun# ./useradd

This will add all the users to the system. Now we have to change the passwords. Let’s say we want username123 as password. So for user arun the password will be arun123, ravi123 for user ravi and so on.

Create another bash file as follows:

root@indiangnu.org:/home/arun# vi userpass

#!/bin/sh

# This script is useful for changing user’s password

# Changing password using this script user must have to change password after next login

for i in `more userlist.txt`

do

echo $i

echo $i”123″ | passwd –stdin “$i”

echo; echo “User $i will be forced to change password on next login!”

done

 

 

 

Save the file and exit.

root@indiangnu.org:/home/arun# chmod 755 userpass

Run the file. All the passwords are changed.

 

The useradd and password changed one time bash script is available below

root@indiangnu.org:/home/arun# vi adduser

#!/bin/sh

# This user.sh script is useful for creating

# bulk number of user account with their password

# This script created by Ravi Bhure (date:14/01/2008)

# For further info please login http://indianGNU.org or

# mail ravi <at> indianGNU.org

#

for i in `more userlist.txt`

do

echo $i

adduser $i

echo $i”123″ | passwd –stdin “$i”

echo; echo “User $i’s password changed!”

echo; echo “User $i will be forced to change password on next login!”

done

====================================================== 

changed the permission 755 “useradd” file.

 

Thank You

Ravi Bhure

Shell script to monitor or watch the disk space

Shell script to monitor or watch the disk space

#!/bin/sh
# Shell script to monitor or watch the disk space
# It will send an email to $ADMIN, if the (free avilable) percentage
# of space is >= 90%
# ————————————————————————-
# Linux shell script to watch disk space (should work on other UNIX oses )
# SEE URL: http://www.indiangnu.org
# set admin email so that you can get email
ADMIN=”ravi@indiangnu.org”
# set alert level 90% is default
ALERT=90
df -H | grep -vE ‘^Filesystem|tmpfs|cdrom’ | awk ‘{ print $5 ” ” $1 }’ | while read output;
do
#echo $output
usep=$(echo $output | awk ‘{ print $1}’ | cut -d’%’ -f1 )
partition=$(echo $output | awk ‘{ print $2 }’ )
if [ $usep -ge $ALERT ]; then
echo “Running out of space \”$partition ($usep%)\” on $(hostname) as on $(date)” |
mail -s “Alert: Almost out of disk space $usep” $ADMIN
fi
done

=================

Thank You,

Ravi Bhure

Shell script to monitor running services such as web/http, ssh, mail etc.

Shell script to monitor running services such as web/http, ssh, mail etc.

#!/bin/bash
# Shell script to monitor running services such as web/http, ssh, mail etc.
# If service fails it will send an Email to ADMIN user
# ————————————————————————-
# See URL for more info
# http://www.indiangnu.org
# —————————————————
# service port
ports=”22 80 25″

# service names as per above ports
service=”SSH WEB MAIL”

# No of services to monitor as per (above ports+1)
SCOUNTER=4

#Email id to send alert
ADMINEMAIL=”ravi@indiangnu.org”

# counter
c=1
echo “Running services status:”

# use sudo if you want i.e. sudo /bin/netstat
/bin/netstat -tulpn | grep -vE ‘^Active|Proto’ | while read LINE
do
sendMail=0
# get active port name and use : as delimiter
t=$(echo $LINE | awk ‘{ print $4}’ | cut -d: -f2)
[ “$t” == “” ] && t=-1 || :
# get service name from $services and : as delimiter
sname=$(echo $service | cut -d’ ‘ -f$c)
sstatus=”$sname: No”
# now compare port
for i in $ports
do
if [ $i -eq $t ]; then
sstatus=”$sname: Ok”
sendMail=1
fi
done
# display service status as OK or NO
echo “$sstatus”
#next service please
c=$( expr $c + 1 )
[ “$sendMail” == “0” ] && echo $sstatus | mail -s “service down $sstatus” $ADMINEMAIL || :
# break afer 3 services
[ $c -ge $SCOUNTER ] && break || :
done

==========================

Thank you

Ravi Bhure

Start & stop oracle service

Start & stop oracle service

This script is useful for start and stop oracle services in *nix OS.

Put this script in /etc/init.d/ with name oracle-start-stop-service.sh & change its permission to 555 (-r-xr-xr-x).

====================

#!/bin/bash
# oracle-start-stop-service.sh
# Run level script to start Oracle 10g services on RedHat Enterprise Linux (RHAS 4)
# Script should work on other UNIX like oses

# ————————————————————————-
# chkconfig: 345 91 19
# description: Startup/Shutdown Oracle service
# ————————————————————————-
# Before using this script check & edit what are your appropriate path and user credentials.
#

OUSER=”oracle”
OPATH=”/home/oracle/oracle/product/10.2.0/db_1″

# check Oracle db status
function chkdb_status() {

# set username
SUSER=”scott”
# set password
SPASS=”123456″

sqlplus -s /nolog > /dev/null 2>&1 <<EOF
whenever sqlerror exit failure
connect $SUSER/$SPASS
exit success
EOF

if [ $? -ne 0 ]; then
echo “Connection failed : DB is down”
exit 1
else
echo “Connection succeeded : DB is up”
fi
}

case “$1” in
start)
echo “*** Starting Oracle *** ”
su – $OUSER -c “$OPATH/bin/lsnrctl start”
su – $OUSER -c “$OPATH/bin/dbstart”
;;
stop)
echo “*** Stopping Oracle *** ”
su – $OUSER -c “$OPATH/bin/lsnrctl stop”
su – $OUSER -c “$OPATH/bin/dbshut”
;;
restart)
$0 stop
$1 start
;;
isqlstart)
echo “*** Starting Oracle iSQL Plus *** ”
su – $OUSER -c “$OPATH/bin/isqlplusctl start”
echo “*** Note: You can access service at url: http://$(hostname):5560/isqlplus”
;;
isqlstop)
echo “*** Stopping Oracle iSQL Plus *** ”
su – $OUSER -c “$OPATH/bin/isqlplusctl stop”
;;
emstart)
echo “*** Starting Oracle Enterprise Manager 10g Database Control ***”
su – $OUSER -c “$OPATH/bin/emctl start dbconsole”
echo “*** Note: You can access service at url: http://$(hostname):1158/em”
;;
emstop)
echo “*** Stopping Oracle Enterprise Manager 10g Database Control ***”
su – $OUSER -c “$OPATH/bin/emctl stop dbconsole”
;;
status)
echo “*** Oracle database status ***”
chkdb_status
;;
*)
echo $”Usage: $0 {start|stop|isqlstart|isqlstop|emstart|emstop}”
exit 1
esac
exit 0

===================

Thank you

Ravi Bhure

Subversion (svn/cvs) repository backup script

Subversion (svn/cvs) repository backup script

By using this script we can take HOT backup and dump of subversion repository.

root@indiangnu.org:/home/arun# cat SVN-Backup.sh

#!/bin/bash

echo -e “Welocme to Subversion Backup utility by Arun Bagul”
echo -e “————————————————————–”

BACKUP_DIR=”/root/SVN_DB_Backup”
choice=$1
repository_path=$2
dest_name=$3
mydate=$(date +%d-%b-%Y)
SVNadmin=$(which svnadmin)
SVNlook=$(which svnlook)
#######################
if [ -d $BACKUP_DIR ]; then
echo “Backup directory $BACKUP_DIR exist”
echo -e “——————————————–”
else
echo “Backup directory $BACKUP_DIR does not exist”
exit
fi
#######################
if [ $# -eq 3 ]; then

case $choice in

dump)

backup_path=”${BACKUP_DIR}/${dest_name}_${mydate}”
#svnadmin path and dump $repository_path $backup_path
echo “Dump of Respository”
#echo “svnadmin dump $repository_path > $backup_path”
$SVNadmin dump $repository_path > $backup_path
;;
hotbkup)

backup_path=”${BACKUP_DIR}/${dest_name}_${mydate}_DIR”
#HotBackup of svn repository
echo “Hot Backup…”
#echo “$SVNadmin hotcopy $repository_path $backup_path”
$SVNadmin hotcopy $repository_path $backup_path
;;
esac
######
elif [ $# -eq 1 ]; then
if [ “$choice” = “lookup” ]; then
#svn look up
$SVNlook youngest $repository_path
fi
else
echo “Usage: SVN-Backup.sh { dump|hotbkup|lookup } repository_path dest file/dir_name”
fi

#####
echo “Done”
exit 0

root@indiangnu.org:/home/arun#

  • How to use this script-

root@indiangnu.org:/home/arun# /sbin/SVN-Backup
Welocme to Subversion Backup utility by Arun Bagul
————————————————————–
Backup directory /root/SVN_DB_Backup exist
——————————————–
Usage: SVN-Backup.sh { dump|hotbkup|lookup } repository_path dest file/dir_name
Done
root@indiangnu.org:/home/arun#

eg (1)-

root@indiangnu.org:~# SVN-Backup dump /usr/local/repos/ myrepos
Welocme to Subversion Backup utility by Arun Bagul
————————————————————————————–
Backup directory /root/SVN_Backup exist
——————————————–
Dump of Respository
* Dumped revision 0.
* Dumped revision 1.
* Dumped revision 2.
* Dumped revision 3.
* Dumped revision 4.
Done

root@indiangnu.org:~#

eg (2)-
root@indiangnu.org:~#SVN-Backup hotbkup /usr/local/repos/ myrepos
Welocme to Subversion Backup utility by Arun Bagul
————————————————————————————–
Backup directory /root/SVN_Backup exist
——————————————–
Hot Backup…
Done
root@indiangnu.org:~#SVN-Backup dump /usr/local/repos/ myrepos

Welocme to Subversion Backup utility by Arun Bagul
————————————————————————————–
Backup directory /root/SVN_Backup exist
——————————————–
Dump of Respository
* Dumped revision 0.
* Dumped revision 1.
* Dumped revision 2.
* Dumped revision 3.
* Dumped revision 4.
Done

root@indiangnu.org:~#SVN-Backup hotbkup /usr/local/repos/ myrepos
Welocme to Subversion Backup utility by Arun Bagul
—————————————————————————————–

Backup directory /root/SVN_Backup exist
——————————————–
Hot Backup…
Done
root@indiangnu.org:~#

Float numbers comparision (shell script)

Float numbers comparision (shell script)

Introduction

Since long time I was thinking about How I can compare float numbers in shell script?.

Finally I got answer of this question!! There is no simple & straight forward way to compare float numbers in shell script….

* There are two ways you can solve this. The first is to actually use some sort of more sophisticated mathematical tool like bc to push out the conditional expression, then test its return value to see if your condition was met or not. That’s a bit tricky, particularly since bc can be difficult to use. Another way to use our own logic with beautiful shell commands

Here is my script with will compare float numbers –

root@indianGNU.org:/home/arun# cat float_compare.sh

#! /bin/bash
RESULT=””
################################
#This function will compare LHS > RHS or not
function is_greater_than ()
{
LHS=$1
RHS=$2
min=$((echo $LHS ; echo $RHS) | sort -n | head -1)
if [ “$min” = “$LHS” ]; then
return 1
else
return 0
fi
}
############################
#This function will compare LHS < RHS or not
is_less_than()
{
LHS=$1
RHS=$2
min=$((echo $LHS ; echo $RHS) | sort -n | head -1)
if [ “$min” = “$LHS” ]; then
return 0
else
return 1
fi
echo $min
}

############################
function compare()
{
function=$1
arg1=$2
arg2=$3
#echo -n “$FUNC $ARG1 $ARG2 … ”
################
$function $arg1 $arg2
if [ $? -eq 0 ]; then
#echo TRUE
RESULT=”TRUE”
else
#echo FALSE
RESULT=”FALSE”
fi
}

############################

num1=$1
num2=$2

if [ “$num1” = “$num2” ]; then
echo “$num1 is equal to $num2”
else
## compare num1 > num2
compare is_greater_than $num1 $num2
if [ “$RESULT” = “TRUE” ] ; then
echo “$num1 > $num2”
fi
## compare num1 < num2
compare is_less_than $num1 $num2
if [ “$RESULT” = “TRUE” ] ; then
echo “$num1 < $num2”
fi
fi

root@indianGNU.org:/home/arun#

How to use or Test this script –

root@indianGNU.org:/home/arun# ./float_compare.sh 2 2.33
2 < 2.33
root@indianGNU.org:/home/arun# ./float_compare.sh 2.60  2.33
2.60 > 2.33
root@indianGNU.org:/home/arun# ./float_compare.sh 56.55  65.80
56.55 < 65.80
root@indianGNU.org:/home/arun# ./float_compare.sh 44.80  44.80
44.80  is equal to 44.80
root@indianGNU.org:/home/arun#

Rsync Client script

Rsync Client script

This is the Rsync client side shell scrpit.. You can specify setting for backup in backup.conf file and set cron job. This script will take backup of mentioned directory of respective users at given time.

1] sample backup file –

root@indiangnu.org:/home/arun# cat /etc/backup/backup.conf

#This is the Backup conf for client
#username:path_to_backup:where_to_backup:when_to_backup:time:
#when_to_backup=> daily=1,weekly=2, monthly=3
#where_to_backup=>USERNAME [server is 192.168.1.50], time=>0930 like 9:30 as 0930
root:/etc/:Server-conf/Fileserver_etc-dir:09:09:no
arun:/home/arun/public_html:arun/bkup:10:09:no
nishit:/home/nishit/public_html:nishit/bkup:11:09:no

root@indiangnu.org:/home/arun#

2] Set cronjob –

#Cronjob for Backup on Fileserver

0 08-12 * * * /etc/backup/rsync-client.sh

3] Rsync client script –

root@indiangnu.org:/home/arun# cat /etc/backup/rsync-client.sh

#!/bin/bash
#User define Function (UDF)……..
HOSTNAME=192.168.1.160

#Process backup.conf
########################################
processLine()
{
#echo $line
#username:path_to_backup:where_to_backup:when_to_backup:time:
username=$(echo $line | awk -F: ‘{ print $1 }’)
path_to_bkup=$(echo $line | awk -F: ‘{ print $2 }’)
where_to_bkup=$(echo $line | awk -F: ‘{ print $3 }’)
when_to_bkup=$(echo $line | awk -F: ‘{ print $4 }’)
time=$(echo $line | awk -F: ‘{ print $5 }’)
status=$(echo $line | awk -F: ‘{ print $6 }’)
#echo “Arg[1]–>”$username
#echo “Arg[2]–>”$path_to_bkup
#echo “Arg[3]–>”$where_to_bkup
#echo “Arg[4]–>”$when_to_bkup
#echo “Arg[5]–>”$time
#echo “Arg[6]–>”$status

#Test the backup.conf
################
if [ “$username” == “” ] ; then
echo “Record is Null”
else
#Check who is running this script root or normal user.
who_is_running=$(id -nu)
#call function to check password file

password_fun $who_is_running $username
system_time=$(date +%H)
if [ “$system_time” == “$time” ] ; then
#call backup function
backup $username $path_to_bkup $where_to_bkup $when_to_bkup $time $status
#echo “system_time=”$system_time
#echo “time=”$time
fi
fi
################
}

#Password Function
########################################
password_fun()
{
#user=”$@” #get all argument
is_root_user=$1
user=$2
#where is secret.conf file
if [ “$is_root_user” == “root” ]; then
if [ “$user” == “root” ]; then
pwd_file=”/root/.secret.conf”
else
pwd_file=”/home/$user/.secret.conf”
fi
#Check file exist or not
if [ ! -f $pwd_file ]; then
echo “$pwd_file file does not exist!”
echo “creating File..”
touch $pwd_file
echo “changing ownership and permission”
owner=”root:root $pwd_file”
echo “owner “$owner
chown root:root $pwd_file
chmod 600 $pwd_file
echo “password” > $pwd_file
#echo $(ls -l $pwd_file)
fi
else
echo “permission denied to read pwd file”
fi
}

#Set ENV variable
########################################
set_ENV_var()
{
user=$1
TERM=xterm
LANGUAGE=en_IN:en
LOGNAME=$user
if [ “$user” == “root” ]; then
USER=root
PWD=/root
HOME=/root
PATH=$PATH:/usr/bin/X11:/usr/games
else
USER=${user}
PATH=/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games
HOME=/home/${user}
PWD=/home/${user}
fi
}
#Backup Function
########################################
backup()
{
username=$1
path_to_bkup=$2
where_to_bkup=$3
when_to_bkup=$4
time=$5
status=$6
echo “——————————————————————”
#command=”/usr/bin/rsync –password-file=”/home/$username/.secret.conf” $path_to_bkup -Cravz 192.168.0.5::$where_to_bkup”
echo “Backup started for ${username}……”
if [ “$username” == “root” ]; then
command=” –password-file=”/root/.secret.conf” ${path_to_bkup} -Cravz 192.168.1.50::${where_to_bkup}”
else
command=” –password-file=”/home/${username}/.secret.conf” ${path_to_bkup} -Cravz 192.168.1.50::${where_to_bkup}”
fi

#Set environment variable…
set_ENV_var $username
#check status ofBackup
if [ “$status” == “no” ] ; then
if [ -f $path_to_bkup ]; then
echo “$path_to_bkup file/dir does exist!”
/usr/bin/rsync $command
elif [ -d $path_to_bkup ]; then
echo “This dirname [$path_to_bkup] does exists”
/usr/bin/rsync $command
else
echo “Neither [$path_to_bkup] or [$path_to_bkup] exist”
fi
if [ $? -eq 0 ]; then
status=”yes”
else
status=”no”
fi
fi
echo “——————————————————————”
#Send mail to user
###########################
if [ $? -eq 0 ]; then
if [ “$username” != “root” ]; then
/etc/backup/mailclient 192.168.1.100 backupmail ${username} ${HOSTNAME}
fi
fi
#Set back env to root…
set_ENV_var root
#Update status function
#update_status $username $status $time
}

#Staus Function

########################################

update_status()
{
status_file=”/etc/backup/backup.status”
new_user=$1
new_status=$2
new_time=$3
update=”${new_user}:${new_status}:${new_time}:”
echo “update string:->”$update
echo “update::status file–>”$status_file
# Read $status_file using the file descriptors
file_string=””
count=”0″
while [ 1 ]
do
read myline || break
username=$(echo $line | awk -F: ‘{ print $1 }’)
if [ “$user” == “$username” ]; then
if [ $count -eq 0 ]; then
file_string=${file_string}${update}
count=`expr $count + 1`
else
file_string=${file_string}
fi
else
file_string=${file_string}${myline}
fi
#save string to file
echo $file_string > $status_file
echo -e “update”
cat $status_file
done < $status_file
#echo “update backup.status file function is end”
}

#Main script stars here
########################################
FILE=””
#Is file name given as command line argument
#Else read it from standard input device
if [ “$1” == “” ]; then
FILE=”/etc/backup/backup.conf”
else
FILE=”$1″
#make sure file exist and readable
if [ ! -f $FILE ]; then
echo “$FILE : does not exists”
exit 1
elif [ ! -r $FILE ]; then
echo “$FILE: can not read”
exit 2
fi
fi
#Read $FILE using the file descriptors
count=”1″
exec 3<&0
exec 0<$FILE
while read line
do
# use $line variable to process line in processLine() function
if [ $count -gt 4 ]; then
processLine $line
else
count=$(expr $count + 1)
fi

done
exec 0<&3
exit 0

root@indiangnu.org:/home/arun#

MySQL full DB dump -shell script

MySQL full DB dump -shell script

#!/bin/bash
#Shell script to backup MySQL database
#To set permission to user which can take  backup of all the DB in
#MySQL server. plzsee query below
#mysql> grant SELECT, LOCK TABLES  on  *.*  to
#’backup_user’@’localhost’ identified  by  ‘pwd_of_user’;
#
#(c)arunbagul@indiangnu.org
###############################################################
#DB details
user_name=”user”
user_pwd=”password”
myhost=”localhost”

# Linux bin paths, change this if it can’t be autodetected via which command
mysql_cmd=”$(which mysql)”
dump_cmd=”$(which mysqldump)”
CHOWN=”$(which chown)”
CHMOD=”$(which chmod)”
zip_cmd=”$(which gzip)”

# Backup Dest directory, change this if you have someother location
dest_dir=”/var/mysql-backup/

# Get hostname
host_name=”$(hostname)”

# Get data in dd-mm-yyyy format
NOW=”$(date +”%d-%m-%Y”)”

# File to store current backup file
FILE=””
# Store list of databases
DB_list=””

# DO NOT BACKUP these databases
Ignore_db=”test”

[ ! -d $MBD ] && mkdir -p $MBD || :

# Only root can access it!
$CHOWN 0.0 -R $dest_dir
$CHMOD 0600 $dest_dir

# Get all database list first
DB_list=”$($mysql_cmd -u$user_name -h $myhost -p$user_pwd   -Bse ‘show
databases’)”

#send db list to file and clear previous  content
echo “” > $mail_file
echo “” > $database_file

for db in $DB_list
do
skipdb=-1
#send DB list to file
echo $db >> $database_file
echo $db
if [ “$Ignore_db” != “” ];
then
for i in $Ignore_db
do
[ “$db” == “$i” ] && skipdb=1 || :
done
fi

if [ “$skipdb” == “-1″ ] ; then
FILE=”$dest_dir/$db.$host_name.$NOW.gz”
my_file=”$dest_dir/${db}_${host_name}.sql”
# do all inone job in pipe,
# connect to mysql using mysqldump for select mysql database
# and pipe it out to gz file in backup dir 🙂
# $dump_cmd -u $user_name -h $myhost -p$user_pwd $db | $zip_cmd -9 > $FILE
# DB dump start here
########################################
$dump_cmd -u $user_name -h $myhost -p$user_pwd $db > $my_file
if [ $? -eq 0 ]; then
echo $db >> $mail_file
fi
########################################
fi
done

#end

python script for sending mail.

python script for sending mail.

#!/usr/bin/python
#This  scritp  will send mail  in both HTML and Text format
#@arunbagul@indiangu.org
#@GPL
import smtplib
import os
import sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

#guess = sys.argv[1]
fromaddr = “arunbagul@indiangnu.org”
toaddrs = “toaddress@indiangnu.org”

#———————————–
file_name = “/home/arunbagul/mail-body.txt”
file = open(file_name)
msg = file.read();
#———————————-
#msg = MIMEMultipart()
#msg[‘From’] = fromaddr
#msg[‘To’] = COMMASPACE.join(toaddrs)
#msg[‘To’] = toaddrs
#msg[‘Date’] = formatdate(localtime=True)
#msg[‘Subject’] = “This is my Sub”

server = smtplib.SMTP(‘192.168.1.5’)
#server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
#server.sendmail(fromaddr, toaddrs, msg.as_string())
server.quit()

Load Balancing – shell script

Load Balancing – shell script

#!/bin/bash
echo “——————————————-”
echo “”
echo -e “Wel come to Load Balancing………….”
echo -e “@arunbagul@indiangnu.org”
echo “”
echo “——————————————-”
#################################
#**root@proxy# cat  /etc/iproute2/rt_tables
#
# reserved values
#
#**255     local
#**254     main
#**253     default
#**0       unspec
#Entry manually added
#please  add this two line each internet connections
#for example two connections
#**251    sify3
#**252    tata
#################################

#specify Details
#Local LAN
LAN_IF=eth0
LAN_IP=192.168.1.68
LAN_NWK=192.168.1.0/24

#INET1 (internet connection )
INET1_IF=eth1
INET1_IP=10.10.172.230
INET1_NWK=10.10.172.0/24
INET1_GW=10.10.172.X

#INET2 (internet connection )
INET2_IF=eth2
INET2_IP=208.259.169.X
INET2_NWK=208.259.169.X/30
INET2_GW=208.259.169.X

#################################
case “$1” in

start)
#Start Load Balancing……..
echo -e “Starting Load Balancing……..”
##################################################################
#step(1)
#Flush out table tata  & sify3 if any routing is their.
/sbin/ip route flush table tata
/sbin/ip route flush table sify3
#################################
echo -e “Creating Kernel routing table::- tata(251)”
# 202.189.249.204/30 is IP n/w of ISP1 with
#gateway is 202.189.249.205 & IP assign
#to eth3  is 202.189.249.206 which is source(src)
/sbin/ip route add $INET2_NWK dev $INET2_IF src $INET2_IP proto kernel table tata
#Add entry for internel n/w
/sbin/ip route add $LAN_NWK dev $LAN_IF proto kernel src $LAN_IP table tata
#Now add default gateway to ISP-I in table tata
/sbin/ip route add default via $INET2_GW table tata
##################################################################
#step(2)
echo -e “Creating Kernel routing table::- sify3(253)”
# 10.10.127.0/24 is IP n/w of ISP2 with
# gateway is 10.10.127.1 & IP assign
#to eth1  is 10.10.127.222 which is source(src)
/sbin/ip route add $INET1_NWK  dev $INET1_IF  src $INET1_IP proto kernel table sify3
#Add entry for internel n/w
/sbin/ip route add $LAN_NWK dev $LAN_IF proto kernel src $LAN_IP table sify3
#Now add default gateway to ISP-II in table sify3
/sbin/ip route add default  via $INET1_GW  table sify3
##################################################################
#step(3)
#set up the routing rules.
#These actually choose what routing table to route with.
/sbin/ip rule  add from $INET2_IP table tata
/sbin/ip rule  add from $INET1_IP table sify3
##################################################################
#step(4)
#Delete default route path form kernel ‘main’ routing table.
/sbin/route del default
if [ $(echo $?) = 0 ] ; then
echo -e “Default gateway removed from ‘main’ table”
fi
/sbin/route del default
echo “Done………”
##################################################################
#step(5)
#now set up the default route to be a multipath route.
#In the default kernel this will balance routes over the two providers.
#/sbin/ip route add default equalize nexthop via $INET1_IP $dev $INET1_IF weight 1 nexthop via $INET2_IP dev $INET2_IF weight 1
/sbin/ip route add default  nexthop  via $INET1_IP dev $INET1_IF weight 1 nexthop via $INET2_IP dev $INET2_IF  weight 1
echo -e ” Thank you….”
##################################################################
;;
stop)
#Stoping Load Balancing….
echo -e “Stoping Load Balancing….”
#Seperating routing decision…
/sbin/ip rule del from $INET1_IP table tata
/sbin/ip rule del from $INET1_IP  table sify3
#Flush out table tata,sify3 and main if any routing is their.
/sbin/ip route flush table tata
/sbin/ip route flush table sify3
/sbin/ip route flush table main
#update kernel ‘main table’————–
#add entry for ‘tata’ connection
/sbin/ip route add $INET2_NWK  dev $INET2_IF  src $INET2_IP  proto kernel  scope link  table main
#add entry for ‘sify’ connection
/sbin/ip route add $INET1_NWK  dev eth1  src $INET1_IP proto kernel  scope link  table main
#Add entry for internel n/w
/sbin/ip route add $LAN_NWK  dev $LAN_IF proto kernel scope link src 192.168.0.3 table main
#Now add default gateway to ISP-I in table main
/sbin/ip route add default via $INET1_GW table main
;;
status)
#Checkng Load Balancing status….
echo -e “Checking Load Bal status…….”
#Check load balancing is successful or not————-
/sbin/ip route show | grep “nexthop” > /dev/null
if [ $(echo $?) = 0 ] ; then
echo -e “Load Balancing is SUCCESSSFUL”
else
echo -e  “Load Balancing FAILED”
echo -e “Load-balancing:: Please try again…”
fi
;;
table)
#Kernel routing table
#################################
echo -e “Kernel routing table ‘tata’ is…..”
/sbin/ip route show table tata
echo -e “Kernel routing table ‘sify3’ is…..”
/sbin/ip route show table sify3
#Now finally check kernel routing with default route as multiple route
echo -e “~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~”
echo -e “Kernel ‘main’ routing table is…(plz check here)”
/sbin/ip route show table  main
echo -e “………..”
/sbin/route -n
echo -e “~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~”
echo -e “!!please run this cmd when ever you will restart n/w service or PC.”
echo -e ” And make sure that both connection are running”
;;

*)
echo “Usage:/sbin/load-balancing {start|stop|status|table}”
exit 1
;;
esac
#################################
#exit 0
#END