ping multiple IP’s using bash?
I have 10 IP numbers which I have to ping daily for checking , How I can do that by using BASH script. So that I can automate that task by using cron. I want BASH script only. Thank you.
Below answer I have mentioned IP’s of Google,yahoo,msn etc. I have tried that myself. Inserting <> and , are not working here between IP’s to separate them. hope it may help somebody in future. Thank you for reading.
7 Answers 7
As your ip range has no symmetry and there are only 10 nodes, I would suggest to list them in a text file. I am considering the file containing the list is list.txt which contains list of ip one at each line as shown below,
10.12.13.14 172.15.48.3 192.168.45.54 . 48.114.78.227
#!/bin/bash # Program name: pingall.sh date cat /path/to/list.txt | while read output do ping -c 1 "$output" > /dev/null if [ $? -eq 0 ]; then echo "node $output is up" else echo "node $output is down" fi done
To update the running status of your nodes at an interval of 30 mins use at crontab,
*/30 * * * * /path/to/pingall.sh > /path/to/log.txt
$ cat /path/to/log.txt Fri Jan 31 15:06:01 IST 2014 node 10.12.13.14 is up node 172.15.48.3 is up node 192.168.45.54 is up . node 48.114.78.227 is down
this seems exactly what OP should be looking for.. and since websites like google.com, yahoo.com, etc. use multiple servers to handle requests it would be better to ping them with their domain names (so that you possibly won’t have to change the IP in your ping-list the coming week)..
#!/bin/bash for i in `seq $ $` do ping -c 1 $.$ > /dev/null 2>&1 if [ $? -eq 0 ]; then echo "$.$ responded." else echo "$.$ did not respond." fi done
To run ./script 192.168.1 0 10 for example this will ckeck the ips 192.168.1.0 to 192.168.1.10 and echo responded if ping is ok and didn’t respond if not.
NB: You can replace $1 $2 $3 by static variables if the range and the IP’s are always the same.
A neat and simple script that could be very useful (i.e: on embedded devices), even when it does not address 100% the conditions of the question. Thanks you. +1 deserved.
Assume that you have 5 IP’s( to reduce the answer only) then you can ping them with
#!/usr/bin/bash for i in xxx.xxx.xxx.xxx xxx.xxx.xxx.xxx xxx.xxx.xxx.xxx xxx.xxx.xxx.xxxx do ping -c 5 $i done
Note: Not curl brackets , No Commas(,) between IP’s.
[raja @ scripts]$ cat ping.sh for i in 74.125.236.70 98.139.183.24 65.55.206.228 91.189.94.156 198.252.206.24 do ping -c 5 $i done [raja @ scripts]$ ./ping.sh PING 74.125.236.70 (74.125.236.70) 56(84) bytes of data. 64 bytes from 74.125.236.70: icmp_seq=1 ttl=128 time=11.5 ms 64 bytes from 74.125.236.70: icmp_seq=2 ttl=128 time=11.0 ms 64 bytes from 74.125.236.70: icmp_seq=3 ttl=128 time=10.9 ms 64 bytes from 74.125.236.70: icmp_seq=4 ttl=128 time=16.5 ms 64 bytes from 74.125.236.70: icmp_seq=5 ttl=128 time=18.2 ms --- 74.125.236.70 ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4025ms rtt min/avg/max/mdev = 10.966/13.682/18.291/3.120 ms PING 98.139.183.24 (98.139.183.24) 56(84) bytes of data. 64 bytes from 98.139.183.24: icmp_seq=1 ttl=128 time=244 ms 64 bytes from 98.139.183.24: icmp_seq=2 ttl=128 time=253 ms 64 bytes from 98.139.183.24: icmp_seq=3 ttl=128 time=255 ms 64 bytes from 98.139.183.24: icmp_seq=4 ttl=128 time=251 ms 64 bytes from 98.139.183.24: icmp_seq=5 ttl=128 time=243 ms --- 98.139.183.24 ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4251ms rtt min/avg/max/mdev = 243.511/249.623/255.275/4.674 ms PING 65.55.206.228 (65.55.206.228) 56(84) bytes of data. From 10.22.96.94 icmp_seq=5 Packet filtered --- 65.55.206.228 ping statistics --- 5 packets transmitted, 0 received, +1 errors, 100% packet loss, time 14002ms PING 91.189.94.156 (91.189.94.156) 56(84) bytes of data. 64 bytes from 91.189.94.156: icmp_seq=1 ttl=128 time=240 ms 64 bytes from 91.189.94.156: icmp_seq=2 ttl=128 time=240 ms 64 bytes from 91.189.94.156: icmp_seq=3 ttl=128 time=240 ms 64 bytes from 91.189.94.156: icmp_seq=4 ttl=128 time=240 ms 64 bytes from 91.189.94.156: icmp_seq=5 ttl=128 time=240 ms --- 91.189.94.156 ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4242ms rtt min/avg/max/mdev = 240.060/240.222/240.309/0.626 ms PING 198.252.206.24 (198.252.206.24) 56(84) bytes of data. 64 bytes from 198.252.206.24: icmp_seq=1 ttl=128 time=237 ms 64 bytes from 198.252.206.24: icmp_seq=2 ttl=128 time=237 ms 64 bytes from 198.252.206.24: icmp_seq=3 ttl=128 time=237 ms 64 bytes from 198.252.206.24: icmp_seq=4 ttl=128 time=237 ms 64 bytes from 198.252.206.24: icmp_seq=5 ttl=128 time=242 ms --- 198.252.206.24 ping statistics --- 5 packets transmitted, 5 received, 0% packet loss, time 4251ms rtt min/avg/max/mdev = 237.600/238.575/242.291/1.933 ms
Linux ping диапазона ip адресов
Иногда возникает необходимость пропинговать множество узлов. Стандартная утилита ping умеет пинговать только один хост. Для того, чтобы пинговать множество хостов, стоит воспользоваться возможностями утилиты fping.
Согласно информации из Википедии:
fping — Свободно распространяемая утилита для UNIX систем. Проверяет доступность узлов в сети путем посылки ICMP ECHO_REQUEST пакетов. В отличие от стандартной утилиты ping, можно указать сколько угодно узлов в командной строке или указать текстовый файл со списком узлов. Вместо того, чтобы послать запрос ожидать ответа от одного узла, fping посылает запрос и переходит к следующему узлу по round-robin.
По умолчанию, когда узел ответил он удаляется из списка узлов для проверки, если же в течение заданного времени и/или количества попыток ответ не пришёл то такой узел считается недоступным. fping может посылать указанное или бесконечное количество запросов, так же, как это делает ping.
В отличие от ping, fping подразумевает использование его в скриптах, поэтому он выводит данные в форме удобной для разбора скриптом (parse).
fping относится к утилитам использующим ping sweep технологию. Вы должны понимать что пингование (сканирование) узлов или сетей которые вам не принадлежат может трактоваться как противозаконное действие.
Исходя из этой информации, можно отметить такие недостатки использования утилиты fping:
- мгновенный скачкообразный ICMP-флуд в ethernet-сегменте;
- мгновенная нагрузка на систему;
- в выводе утилиты fping имеют место быть не только IP-адреса ответивших хостов, т.е. его нужно еще дополнительно фильтровать;
- неприемлемое для больших сетей (несколько тысяч хостов) быстродействие.
Но в определенных ситуациях использование утилиты может пригодиться.
Выполним установку fping из системы портов:
# cd /usr/ports/net/fping && make install clean && rehash
После установки можно некоторыми возможностями утилиты.
Воспользовавшсь ключем -v, можно просмотреть версию утилиты:
Чтобы ознакомиться с доступными для использования ключами, необходимо использовать ключ -h:
# fping -h Usage: fping [options] [targets. ] -a show targets that are alive -A show targets by address -b n amount of ping data to send, in bytes (default 68) -B f set exponential backoff factor to f -c n count of pings to send to each target (default 1) -C n same as -c, report results in verbose format -e show elapsed time on return packets -f file read list of targets from a file ( - means stdin) (only if no -g specified) -g generate target list (only if no -f specified) (specify the start and end IP in the target list, or supply a IP netmask) (ex. fping -g 192.168.1.0 192.168.1.255 or fping -g 192.168.1.0/24) -i n interval between sending ping packets (in millisec) (default 25) -l loop sending pings forever -m ping multiple interfaces on target host -n show targets by name (-d is equivalent) -p n interval between ping packets to one target (in millisec) (in looping and counting modes, default 1000) -q quiet (don't show per-target/per-ping results) -Q n same as -q, but show summary every n seconds -r n number of retries (default 3) -s print final stats -S addr set source address -t n individual target initial timeout (in millisec) (default 500) -u show targets that are unreachable -v show version targets list of targets to check (if no -f specified)
Пример пингования сети 172.20.0.0/28:
# fping -g 172.20.0.0/28 172.20.0.1 is alive 172.20.0.5 is alive 172.20.0.9 is alive 172.20.0.12 is alive 172.20.0.13 is alive 172.20.0.0 is unreachable 172.20.0.2 is unreachable 172.20.0.3 is unreachable 172.20.0.4 is unreachable 172.20.0.6 is unreachable 172.20.0.7 is unreachable 172.20.0.8 is unreachable 172.20.0.10 is unreachable 172.20.0.11 is unreachable 172.20.0.14 is unreachable 172.20.0.15 is unreachable
Если использовать ключ -a, то в выводе утитилы будут присутствовать только доступные хосты:
# fping -ag 172.20.0.0/28 172.20.0.1 172.20.0.5 172.20.0.9 172.20.0.12 172.20.0.13
Для отображения времени отклика необходимо использовать ключ -e:
# fping -aeg 172.20.0.0/28 172.20.0.1 (0.05 ms) 172.20.0.5 (1.15 ms) 172.20.0.9 (1.18 ms) 172.20.0.12 (1.21 ms) 172.20.0.13 (0.92 ms)
Для формирования отчета необходимо использовать ключ -s:
# fping -saeg 172.20.0.0/28 172.20.0.1 (0.04 ms) 172.20.0.5 (1.09 ms) 172.20.0.9 (1.06 ms) 172.20.0.12 (1.06 ms) 172.20.0.13 (0.98 ms) 16 targets 5 alive 11 unreachable 0 unknown addresses 44 timeouts (waiting for response) 49 ICMP Echos sent 5 ICMP Echo Replies received 0 other ICMP received 0.04 ms (min round trip time) 0.84 ms (avg round trip time) 1.09 ms (max round trip time) 6.352 sec (elapsed real time)
Краткий обзор утилиты сделан, и ее возможности более-менее понятны.
Ping range of IP addresses in parallel with fping
fping is a program which uses the Internet Control Message Protocol (ICMP) echo request to determine if a host is up. fping is different from ping in that you can specify any number of hosts on the command line, or specify a file containing the lists of hosts to ping. Instead of trying one host until it timeouts or replies, fping will send out a ping packet and move on to the next host in a round-robin fashion. If a host replies, it is noted and removed from the list of hosts to check. If a host does not respond within a certain time limit and/or retry limit it will be considered unreachable.
Basically fping is meant to be used in shell scripts and its output is easy to parse. This command can be very useful to when you have to scan whole network for alive or unreachable hosts. In case of usage regular ping command you’ll have to write shell script and parse each hosts icmp replies but fping can do the same in one line:
To scan range of IP addresses from 192.168.0.1 to 192.168.0.9 just run:
sudo fping -s -g 192.168.0.1 192.168.0.9 -r 1
192.168.0.1 is alive
192.168.0.7 is alive
192.168.0.2 is unreachable
192.168.0.3 is unreachable
192.168.0.4 is unreachable
192.168.0.5 is unreachable
192.168.0.6 is unreachable
192.168.0.8 is unreachable
192.168.0.9 is unreachable
9 targets
2 alive
7 unreachable
0 unknown addresses
14 timeouts (waiting for response)
16 ICMP Echos sent
2 ICMP Echo Replies received
0 other ICMP received
0.05 ms (min round trip time)
0.44 ms (avg round trip time)
0.84 ms (max round trip time)
2.183 sec (elapsed real time)
In order to scan /24 network (254 hosts) and show only alive hosts the following command can be used:
sudo fping -a -q -g 192.168.0.0/24