Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

bash - I am not able to Ping IPs from my indexed array but works with an associative array

I am trying to iterate IPs which are read from a csv to an array as a kind of monitoring solution. I have the ips in a indexed array and want to pass the ips to the ping command but its not working.

#!/bin/bash
datei=hosts.csv
length=$(cat $datei  | wc -l)

for (( i=1; i<=$length; i++ ))
do
ips[$i]=$(cut -d ';' -f2 $datei | awk 'NR=='$i'')
hosts[$i]=$(cut -d ';' -f1 $datei | awk 'NR=='$i'')
done

servers=( "1.1.1.1" "8.8.4.4" "8.8.8.8" "4.4.4.4")

for i in ${ips[@]} #Here i change the array i want to iterate
do
echo $i
ping -c 1 $i > /dev/null
        if [ $? -ne 0 ]; then
        echo "Server down"
        else
        echo "Server alive"
        fi
done

Interesting is that if I iterate the server array instead of the ips array it works. The ips array seems from data fine if printed.

The output if I use the servers array:

1.1.1.1
Server alive
8.8.4.4
Server alive
8.8.8.8
Server alive
4.4.4.4
Server down

and if I use the ips array

1.1.1.1
: Name or service not known
Server down
8.8.4.4
: Name or service not known
Server down
8.8.8.8
: Name or service not known
Server down
4.4.4.4
: Name or service not known
Server down

Output from cat hosts.csv

test;1.1.1.1
test;8.8.4.4
test;8.8.8.8
test;4.4.4.4

First column is for Hostnames and the second column for the IPs in v4.

I am on Ubuntu 20.4.1 LTS

question from:https://stackoverflow.com/questions/65938640/i-am-not-able-to-ping-ips-from-my-indexed-array-but-works-with-an-associative-ar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Fixed multiple issues with your code:

  • Reading of hosts.csv into arrays.
  • Testing the ping result.

hosts.csv:

one.one.one.one;1.1.1.1
dns.google;8.8.4.4
dns.google;8.8.8.8
invalid.invalid;4.4.4.4

Working commented in code:

#!/usr/bin/env bash

datei=hosts.csv
# Initialize empty arrays
hosts=()
ips=()

# Iterate reading host and ip in line records using ; as field delimiter
while IFS=; read -r host ip _; do
  hosts+=("$host") # Add to the hosts array
  ips+=("$ip") # Add to the ips array
done <"$datei" # From this file

# Iterate the index of the ips array
for i in "${!ips[@]}"; do
  # Display currently processed host and ip
  printf 'Pinging host %s with IP %s
' "${hosts[i]}" "${ips[i]}"

  # Test the result of pinging the IP address
  if ping -nc 1 "${ips[i]}" >/dev/null 2>&1; then
    echo "Server alive"
  else
    echo "Server down"
  fi
done

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...