multiple methods of for cycle in shell and reachability test
1. Like C program
#!/bin/bash
for ((i=1;i<=100;i++))
do
echo $i
done
2 . Block of code
#!/bin/bash
for i in {1..100}
do
echo $i
done
3. seq mode
#!/bin/bash
for i in `seq 1 100`
do
echo $i
done
Result of execution
[root@AMH ~]# bash for.sh
1
2
3
4
5
6
7
.
100
Insert a mass of ip in /opt/ip.txt , one ip for each row,
and detect the reachability of all ip address by a shell script.
#/bin/bash
for ip in `cat /opt/ip.txt`
do
ping $ip -c 2 >> /dev/null 2>&1
if [ $? -eq 0 ]; then
echo $ip is up
else
echo $ip is down
fi
done
Result of execution
[root@localhost ~]# bash ip_new.sh
10.8.37.67 is up
10.8.20.35 is up
10.8.23.223 is up
10.8.23.43 is down
10.8.39.19 is down
10.8.24.95 is down
10.8.20.63 is up
10.8.14.207 is down
10.8.23.59 is down
Enrich content of this script, confirming whether port 36566 is opening or
not if ip can ping.
#/bin/bash
package=`rpm -qa | grep ^nc-`
if [ $package != `rpm -qa | grep ^nc-` ]; then
echo “preparing…”
yum install nc -y >>/dev/null
else
echo “nc has been installd”
fi
for ip in `cat /opt/ip.txt`
do
ping $ip -c 2 >> /dev/null 2>&1
if [ $? -eq 0 ]; then
echo -e $ip is up “\c”
sshd_port=`nc -w 10 -z $ip 36566 | awk ‘{print $7}’`
if [ “$sshd_port” == “succeeded!” ]; then
echo “port 36566 ok”
else
echo “port 36566 error”
fielse
echo $ip is down
fi
done
Result of execution
[root@localhost ~]# bash ip_new.sh
nc has been installd
10.8.38.35 is up port 36566 ok
10.8.37.63 is down
10.8.23.11 is down
10.8.39.15 is up port 36566 error
10.8.23.43 is up port 36566 ok
10.8.24.115 is down
10.8.38.139 is up port 36566 ok