lundi 6 mars 2017

Bash If statement in for loop in if statement

Preface: I hate to ask 2 questions in one day, but I have a lot of studying to do and I have been stuck on this for quite awhile. I have searched for hours and can't seem to find a solution that works. I have modified this code countless times, and I just cant get it working. I am just learning bash and the syntax is pretty foreign to me. I'm sure that I have made another noob mistake in the following code. I just cant seem to find where.

Code:

#!/bin/bash

ip=$1
first=$2
last=$3

if (( $first >= 1 && $first <= 255 && $last >= 1 && $last <= 255 && $first <= $last)); then

    range=0

else
    range=1
    fi




if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0]$ ]]; then
    OIFS=$IFS
    IFS='.'
    ip=($ip)
    IFS=$OIFS
    [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
        && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]


    VIP=0
else
    VIP=1
    fi

if (( $range == 0 && $VIP == 0)); then

   echo "intiating ping scan for $1 $first-$last"
   echo ""
   echo "==================================================="
   for i in $(seq $first $last); do ping -c 1 ${ip[0]}.${ip[1]}.${ip[2]}.$i > /dev/null;done
       if [ $? -eq 0 ]; then
           echo "${ip[0]}.${ip[1]}.${ip[2]}.$i is up"
       else
           echo "${ip[0]}.${ip[1]}.${ip[2]}.$i is down"
           fi
else
    echo "invalid IP or range"
    echo "=================================================="
    echo "Usage: ./ping_scan.sh <ip[must end in 0]{ex. 192.168.5.0}> "
    echo "<start address {ex. 23}> <end address {ex. 254}>"
    fi

The issue that I am having revolves around this code snippet:

if (( $range == 0 && $VIP == 0)); then

echo "intiating ping scan for $1 $first-$last"
echo ""
echo "==================================================="
for i in $(seq $first $last); do ping -c 1 ${ip[0]}.${ip[1]}.${ip[2]}.$i > /dev/null;done
   if [ $? -eq 0 ]; then
       echo "${ip[0]}.${ip[1]}.${ip[2]}.$i is up"
   else
       echo "${ip[0]}.${ip[1]}.${ip[2]}.$i is down"
       fi
else
echo "invalid IP or range"
echo "=================================================="
echo "Usage: ./ping_scan.sh <ip[must end in 0]{ex. 192.168.5.0}> "
echo "<start address {ex. 23}> <end address {ex. 254}>"
fi

I used set -x to confirm my suspicions. The issue I am having is I am only receiving output from the last IP address that is being pinged.

The for loop is running for each IP, completing, getting $? for the last ip pinged, then the script is moving into the if statement and printing the status of the final IP.

I need the for loop to run for each IP and the if statement to run for each IP and output the status of each, I know this can be done, and I have tried multiple configurations but none seem to work.

Any advice or a pointer to something to read would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire