使用 bash 数组循环文件中的 IP 地址

问题描述 投票:0回答:2

我有一个文件,其中给出了所有 IP 地址。该文件如下所示:

[asad.javed@tarts16 ~]#cat file.txt
10.171.0.201
10.171.0.202
10.171.0.203
10.171.0.204
10.171.0.205
10.171.0.206
10.171.0.207
10.171.0.208

我一直在尝试通过执行以下操作来循环 IP 地址:

launch_sipp () {
        readarray -t sipps < file.txt
        for i in "${!sipps[@]}";do
                ip1=(${sipps[i]})
                echo $ip1
                sip=(${i[@]})
                echo $sip
        done

但是当我尝试访问该阵列时,我只得到最后一个 IP 地址,即 10.171.0.208。这就是我尝试在同一函数中访问的方式launch_sipp():

local sipp=$1
echo $sipp
Ip=(${ip1[*]})
echo $Ip

目前我在同一个脚本中有 IP 地址,并且我有其他函数正在使用这些 IP:

launch_tarts () {
        local tart=$1
        local ip=${ip[tart]}

        echo "    ----  Launching Tart $1  ----  "
        sshpass -p "tart123" ssh -Y -X -L 5900:$ip:5901 tarts@$ip <<EOF1
        export DISPLAY=:1
        gnome-terminal -e "bash -c \"pwd; cd /home/tarts; pwd; ./launch_tarts.sh exec bash\""
        exit
EOF1
}

kill_tarts () {
        local tart=$1
        local ip=${ip[tart]}

        echo "    ----  Killing Tart $1  ----   "
        sshpass -p "tart123"  ssh -tt -o StrictHostKeyChecking=no tarts@$ip <<EOF1
        . ./tartsenvironfile.8.1.1.0
        nohup yes | kill_tarts mcgdrv &
        nohup yes | kill_tarts server &
        pkill -f traf
        pkill -f terminal-server
        exit
EOF1
}

ip[1]=10.171.0.10
ip[2]=10.171.0.11
ip[3]=10.171.0.12
ip[4]=10.171.0.13
ip[5]=10.171.0.14

case $1 in
        kill) function=kill_tarts;;
        launch) function=launch_tarts;;
        *) exit 1;;
esac

shift

for ((tart=1; tart<=$1; tart++)); do
       ($function $tart) &
       ips=(${ip[tart]})
       tarts+=(${tart[@]})
done
wait

如何将不同的 IP 列表用于从文件中为不同目的创建的函数?

bash
2个回答
3
投票

使用GNU并行怎么样?这是一个非常强大、令人惊奇、非常流行的免费 Linux 工具,易于安装。

首先,这是一个基本的
parallel
工具使用示例:

$ parallel echo {} :::: list_of_ips.txt 
 # The four colons function as file input syntax.†
10.171.0.202
10.171.0.201
10.171.0.203
10.171.0.204
10.171.0.205
10.171.0.206
10.171.0.207
10.171.0.208

†(特定于并行;请参阅此处并行使用备忘单)。

但是您可以用您可以想象的任何复杂的命令系列/调用其他脚本来替换

echo
parallel
循环它接收到的输入并对每个输入执行(并行)相同的操作。

现在,更具体地解决您的问题,您可以简单地将
echo
(上面)替换为对脚本的命令调用:

$ parallel process_ip.sh :::: list_of_ips.txt

现在您不再需要通过 ip 本身处理任何循环,而是专门为单个 IP 输入而编写。

parallel
将处理运行程序并行(您可以使用选项
-j n
为任何int
n
自定义设置并发作业的数量)。

默认情况下

parallel
将作业数量设置为它自动确定您的计算机可用的 vCPU 数量。


1
投票

在纯 Bash 中:

#!/bin/bash
while read ip; do
    echo "$ip"
    # ...
done < file.txt

或并行:

#!/bin/bash
while read ip; do
    (
        sleep "0.$RANDOM" # random execution time
        echo "$ip"
        # ...
    ) &
done < file.txt
wait
© www.soinside.com 2019 - 2024. All rights reserved.