如何在bash中一次读取和运行命令10行?

时间:2015-12-31 22:59:10

标签: bash shell

我有一个bash脚本,通过SSH连接到服务器来运行命令。该脚本从文件中获取IP地址。

问题:如果文件中有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

2 个答案:

答案 0 :(得分: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参数告诉并行一次可以激活多少个作业。

答案 1 :(得分: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