问题描述
我正在尝试迭代从 csv 读取到数组的 IP,作为一种监控解决方案。我有一个索引数组中的 ips,想将 ips 传递给 ping 命令,但它不起作用。
#!/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
有趣的是,如果我迭代服务器数组而不是 ips 数组,它就可以工作。如果打印,ips 数组从数据中看起来很好。
如果我使用服务器数组的输出:
1.1.1.1
Server alive
8.8.4.4
Server alive
8.8.8.8
Server alive
4.4.4.4
Server down
如果我使用 ips 数组
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
来自 cat hosts.csv 的输出
test;1.1.1.1
test;8.8.4.4
test;8.8.8.8
test;4.4.4.4
第一列是主机名,第二列是 v4 中的 IP。
我使用的是 Ubuntu 20.4.1 LTS
解决方法
修复了代码的多个问题:
- 将
hosts.csv
读入数组。 - 测试 ping 结果。
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
在代码中注释的工作:
#!/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\n' "${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
,
您可以使用 readarray 从 stdin 读入数组,然后将其与 awk 结合以解析 Host.csv 文件:
readarray -t ips <<< "$(awk -F\; '{ print $2 }' $date1)"
readarray -t hosts <<< "$(awk -F\; '{ print $1 }' $date1)"