繁体   English   中英

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

[英]Looping over IP addresses from a file using bash array

我有一个文件,其中提供了所有 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 列表?

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

例如,

$ parallel echo {} :::: ips.txt 
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 / 调用其他脚本。 并行循环遍历它接收到的输入,并对每个输入执行(并行)相同的操作。

在纯 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM