簡體   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