Monday, June 19, 2006

Checking the network with bash

Some bash coding
Ok, I posted this somewhere, but I can't remember where :)
I made a bash script for scanning a sub-network to know which computers are up. I know that nping and anothers programs do this, but I wanted to do it by myself using a shell script, and this is how I did it in the first place:
#!/usr/bin/env bash

PING="$(which ping) -c 1 -W 1"

for((i=1;i<255;i++)); do
${PING} ${1}.${i}
if [ $? -eq 0 ]; then
echo -e "${1}.${i} is up"
fi
done

When I ran that script, it worked fine, but very slowly... so I modified it to be this way:
#!/usr/bin/env bash

function pinging(){
SUBNET=${1}
LAST=${2}
PING="$(which ping) -c 1 -W 1"
${PING} ${SUBNET}.${LAST} > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo -e "${SUBNET}.${LAST} is up"
fi
}

if [ -z ${2} ]; then
for((x=1;x<255;x++)); do
${0} ${1} ${x} &
done
else
pinging ${1} ${2}
fi

I hope this will be useful for someone to use it as learning material (this is not the right thing to do because there are applications availble for this)

3 comments:

Anonymous said...

Don't you should check the value of "ulimit -u" before doing this? As this spawn 254 processes, this could be a problem and the script fail

Nomius said...

Yes, actually, if ulimit -u is less than 256 (bash, the main script and those childs),you can maybe get some hosts unscanned, it depends on the speed those process die.
Of course, you get the same problem with any application that use any exec*() system call.

But this was kind of learning material, and for my own use at my laptop computer.
Actually, this was made in a first place in a shopping using a wireless connection. The idea was to check what other computers was connected to a certain access point. I didn't have utils to check that so I made a fast and easy solution.

BTW, it was good that you have noted that.

GGuille said...

Si al guión no se le pasan los parámetros larga una increíble cantidad de procesos. Es conveniente agregarle un

If [ -z $1 ]; then echo "Instrucciones de uso blah blah blah"; exit; fi

antes del if [ -z ${2} ]; then

Saludossssss