Wednesday, 20 March 2013

Shell Script Examples

1. Shell Script : Find All Zip / Rar Files Then Unzip / Unrar

Shell Script

Server1:~$ cat rar.sh

#!/bin/bash #this line must be in every bash script, just ensure that you use correct path

list=`find /home/yevhen/ -type f -name “*.rar”` # get list of file and write this list to variable with name list, find command used to find all files (-type f) where name match *.rar (-name key)

for line in $list; do # this line take every line from list to line variable

DEST=${line%/*} # remove from line filename, so just destination will be in DEST variable.

unrar x $line $DEST # unrar file from line variable to DEST dir

done # finish of for loop.

Output

    Server1:~$ ./rar.sh

    UNRAR 3.93 freeware Copyright (c) 1993-2010 Alexander Roshal

    Extracting from /home/yevhen/Dropbox/Yevhen/test.rar

    Extracting /home/yevhen/Dropbox/Yevhen/wget.sh OK
    All OK

    UNRAR 3.93 freeware Copyright (c) 1993-2010 Alexander Roshal

    Extracting from /home/yevhen/Pictures/test.rar

    Extracting /home/yevhen/Pictures/wget.sh OK
    All OK


===============================================30000
2. Shell Script To Check Disk Usage Is Out Of Space

Shell Script

    #!/bin/bash

    threshold=”20″ # This set threshold value

    i=2 #Counter, will be used later, set to 2, since first line in df output is description.

    result=`df -kh |grep -v “Filesystem” | awk ‘{ print $5 }’ | sed ‘s/%//g’` # Getting list of percentage of all disks, df -kh show all disk usage, grep -v – without description line, awk ‘{ print $5 }’ – we need only 5th value from line and sed ‘s/%//g’ – to remove % from result.

    for percent in $result; do # for every value in result we start loop.

    if ((percent > threshold)) # compare, if current value bigger than threshold, if yes next lines.
    then

    partition=`df -kh | head -$i | tail -1| awk ‘{print $1}’` # taking name of partition, here we use counter. Df list of all partitions, head – take only $i lines from top, tail -1 take only last line, awk ‘{print $1}’ – take only first value in line.

    echo “$partition at $(hostname -f) is ${percent}% full” #print to console – what partition and how much used in %.

    fi # end of if loop

    let i=$i+1 # counter increased by 1.

    done # end of for loop.

Shell Script Result


    Server:~/$ df -kh
    Filesystem Size Used Avail Use% Mounted on
    /dev/sda1 52G 4.7G 45G 10% /
    tmpfs 1.9G 0 1.9G 0% /lib/init/rw
    udev 1.9G 192K 1.9G 1% /dev
    tmpfs 1.9G 2.6M 1.9G 1% /dev/shm
    /dev/sda6 92G 22G 66G 25% /home

    Server:~/$ ./df_script.sh
    /dev/sda6 at yevhen.lviv.example.com is 25% full

==========================================
3. Shell Script : Check Ping To Remote Host And Port Opened

Shell Script

Test Ping And Open Port

    #!/bin/bash

    # check if service name passed to script as argument, if there no arguments (0) do next

    if [ "$#" = "0" ];

    then

    #write to terminal usage

    echo “Usage: $0 ”

    #since no arguments – we need to exit script and user re-run

    exit 1
    fi

    #writing parameters to variables

    host=$1
    port=$2
    email=”test@expertslogin.com”
    subject=”Script result”

    #Check if ping ok -q to quite mod, -c 4 for 4 checks

    if ping -q -c 4 $host >/dev/null
    then
    # next lines writes result variable

    ping_result=”OK”
    else
    ping_result=”NOT OK”

    fi #end of fi loop

    #next command check if port opened via nc command, and getting exit status of nc command

    nc_result=`nc -z $host $port; echo $?`

    #check of exit status of nc command, and write results to variables

    if [ $nc_result != 0 ];
    then
    port_result=”not opened”
    else
    port_result=”opened”
    fi #exit of fi loop

    #writing message that script will email and write to output

    message=”Ping to host – ${ping_result}, port $port ${port_result}.”

    #next check if ping or port check is failed (ping if not OK and exit status of nc if not 0)

    if [ "$ping_result" != "OK" -o "$nc_result" != "0" ];
    then
    echo “$message” #this line write warning message to terminal

    echo “$message” | mail -s “$subject” $email #this line send email

    fi

< h3="">

Ping to localhost and check is 22 port opened (ssh server)

    desktop:~/$ ./script 127.0.0.1 22
    Ping to host – OK, port 22 not opened.
    desktop:~/$

<>


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

4. Shell Script : Service Status Check And start If It’s Not Running

Shell Script

    #!/bin/bash

    if [ "$#" = 0 ] # check if service name passed to script as argument, if there no arguments (0) do next

    then
    echo “Usage $0 ” #write to terminal usage

    exit 1 #since no arguments – we need to exit script and user re-run it

    fi

    service=$1 #get service name from first argument

    is_running=`ps aux | grep -v grep| grep -v “$0″ | grep $service| wc -l | awk ‘{print $1}’` #this check
    #if service running using ps command, after we remove our process from output, since script will also
    # match, with wc we count number of matching lines .

    if [ $is_running != "0" ] ; # is number of lines are not 0 do next

    then

    echo “Service $service is running” #just put this line to terminal

    else #if number of precesses is 0

    echo “Service $service is not running” #just put this string to terminal

    initd=`ls /etc/init.d/ | grep $service | wc -l | awk ‘{ print $1 }’` #checking for files in /etc/init.d
    #(directory with start-up scripts) with name similar to service

    if [ $initd = "1" ]; #if there is script with similar name

    then
    startup=`ls /etc/init.d/ | grep $service` # this line get name of startup script (ls –
    # lists files in directory

    echo -n “Found startap script /etc/init.d/${startup}. Start it? Y/n ? ” #just put to
    #terminal this line

    read answer #waiting for user answer

    if [ $answer = "y" -o $answer = "Y" ]; #if answer Y or y

    then
    echo “Starting service…”

    /etc/init.d/${startup} start # running startup script

    fi #exit of if loop

    fi #exit of if loop

    fi#exit of if loop

Results

    server:~/$ ./service.sh apparmor
    Service apparmor is not running
    Found startap script /etc/init.d/apparmor. Start it? Y/n ? Y
    Starting service…
    * Starting AppArmor profiles [OK]

3 comments: