I am trying to ping a range of IP addresses using Bash and generate a CSV file with the results.
My current code is as follows:
CSV_FILE="ping_results.csv"
echo "IP Address,Status" > $CSV_FILE
for i in {1..254}; do (host 10.184.2.$i | grep "name pointer" >/dev/null && echo "10.184.2.$i;Ping_Yes;$(host 10.184.2.$i | awk '{print $5}' | tr -d '.')" >> ping_results.csv || ping 10.184.2.$i -c 1 -w 5 >/dev/null && echo "10.184.2.$i;Ping_Yes;" >> ping_results.csv) &
done
echo "Ping-Ergebnisse wurden in ping_results.csv gespeichert."
The issue I'm facing is that sometimes the code reports that an IP address is pingable, but when I try to ping it manually, it's not actually reachable. I need help understanding why this is happening and how I can improve the code to ensure that the CSV file only contains accurate information about which IP addresses are actually pingable.
Ideally, the CSV file should contain the following information for each IP address:
- IP Address
- Status (
Ping_Yes
orPing_No
) - Hostname
My goal is to have a reliable and accurate CSV file that correctly identifies the pingable and non-pingable IP addresses within the specified range. How can I achieve this?
Here is the above code written more legibly:
CSV_FILE="ping_results.csv"
echo "IP Address,Status" > $CSV_FILE
for i in {1..254}; do
(
host 10.184.2.$i |
grep "name pointer" >/dev/null &&
echo "10.184.2.$i;Ping_Yes;$(host 10.184.2.$i | awk '{print $5}' | tr -d '.')" >> ping_results.csv ||
ping 10.184.2.$i -c 1 -w 5 >/dev/null &&
echo "10.184.2.$i;Ping_Yes;" >> ping_results.csv
) &
done
echo "Ping-Ergebnisse wurden in ping_results.csv gespeichert."