#!/bin/bash
range=$(seq -f "ma%04g" 5001 5505)
for n in $range;do
ping -q -c 1 -w 3 -s 10 $n >/dev/null
if [ $? -eq 0 ];then
awk -F, -v key="${n}" -v val="up" -v OFS="," '$1==key{$2=val}' /tmp/master.csv > /tmp/temptest.csv
cp /tmp/temptest.csv /tmp/master.csv
else
awk -F, -v key="${n}" -v val="down" -v OFS="," '$1==key{$2=val}' /tmp/master.csv > /tmp/temptest.csv
cp /tmp/temptest.csv /tmp/master.csv
done
不确定我是否在本论坛的任何地方提出了相同的查询,但只是想知道如何使用 xargs 或并行加速此过程,以便获得结果。它还会使 /tmp/master.csv 文件变空吗?
答案1
Gnuparallel
可以轻松运行循环,但是,您不应该在每次迭代时修改 CSV 文件。最好将输出收集到新文件中,然后将其合并到现有 CSV 中,或者如果其中没有特定于节点的数据,则从头开始编写整个新 CSV 文件。
答案2
do_one() {
n="$1"
if ping -q -c 1 -w 3 -s 10 $n >/dev/null ; then
echo up
else
echo down
fi
}
export -f do_one
seq -f "ma%04g" 5001 5505 | parallel -j0 --tag do_one {} > results
# results contains host \t up_or_down
# create files with only hostnames for up
grep up results | awk -e '{print $1}' > up-hosts
# create files with only hostnames for down
grep down results | awk -e '{print $1}' > down-hosts
# This perl script takes 1 second to run if you have 100000 hosts
perl -i.bak -ape 'BEGIN {
# make fast lookup hash for up/down hosts
chomp(@up=`cat up-hosts`);
@up{@up} = @up;
chomp(@down=`cat down-hosts`);
@down{@down} = @down;
}
sub updown {
my $host = shift;
my $last = shift;
if($up{$host}) { return "$host up" };
if($down{$host}) { return "$host down" };
return "$host $last";
}
# $1 = hostname, $2 = up/down of master.csv
s/^(\S+)\s+(\S+)/updown($1,$2)/gme;' master.csv