2015-12-31 91 views
2

我有一個bash腳本,通過SSH連接到服務器來運行命令。該腳本從文件獲取IP地址。如何在bash中一次讀取和運行10行命令?

問題:如果文件中有500個IP,我不想同時打開或嘗試打開500個連接。我想說的是,爲了節省資源,一次10個。

如何通過SSH 10服務器一次運行命令?

這裏是我的腳本:

#/bin/bash 

nodes="big_list_of_nodes.txt" 

while read node; do 
    # Running in background 
    (uptime=`ssh -o ConnectTimeout=5 $node uptime 2>&1` 
    if [ $? -eq 0 ]; then 
     echo "$node uptime: $uptime" 
    else 
     echo "Connection timeout for node $node" 
    fi) & 
done < $nodes 
# Wait for all jobs to finish  
wait 
+1

保留一個計數器,並添加10個IP對數組。當計數達到10時,建立連接,等到他們完成後,取消設置陣列,將計數重置爲0,重複。 –

+1

您是否安裝了[GNU parallel](https://en.wikipedia.org/wiki/GNU_parallel)? (或者您是否願意安裝它?) – ruakh

回答

1

你想編寫一個函數來爲你做所有這需要一個IP地址作爲參數的工作。然後使用parallel文件中讀取和分配工作的功能:

function get_uptime() 
{ 
    node=$1 

    uptime=`ssh -o ConnectTimeout=5 $node uptime 2>&1` 
    if [ $? -eq 0 ]; then 
     echo "$node uptime: $uptime" 
    else 
     echo "Connection timeout for node $node" 
    fi 
} 

export -f get_uptime 

parallel -j 10 --will-cite -a big_list_of_nodes.txt get_uptime 

-j參數告訴平行許多工作如何能在同一時間內。

+2

如果您想要與函數並行使用,則必須先導出該函數。 – 4ae1e1

+0

確實。謝謝,將編輯 – Turn

+0

' - will-cite'選項會做什麼? – GreenTeaTech

0

我能弄明白並使其工作。

我將N行添加到數組,然後處理該數組中的所有內容。然後數組是空的,重複這個過程。

通過這種方式,您可以擁有一個包含數百個主機名或IP地址並以N個塊處理的文件。

#/bin/bash 

nodes=`cat big_list_of_nodes.txt` 

for node in $nodes 
do 
    array+=($node) 
    if [ ${#array[@]} -gt 10 ]; then 
     for n in ${array[@]} 
     do 
     (uptime=`ssh -o ConnectTimeout=5 $n uptime 2>&1` 
     if [ $? -eq 0 ]; then 
      echo "$n uptime: $uptime" 
     else 
      echo "Connection timeout for node $n" 
     fi) & 
     done 
     wait 
     array=() 
    fi 
done 

    if [ ${#array[@]} -gt 0 ]; then 
    for n in ${array[@]} 
     do 
     (uptime=`ssh -o ConnectTimeout=5 $n uptime 2>&1` 
     if [ $? -eq 0 ]; then 
      echo "$n uptime: $uptime" 
     else 
      echo "Connection timeout for node $n" 
     fi) & 
     done 
     wait 
    fi