Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在bash中一次读取和运行10行命令?_Bash_Shell - Fatal编程技术网

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

如何在bash中一次读取和运行10行命令?,bash,shell,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 $

我有一个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
#/bin/bash
nodes=“big\u list\u of\u nodes.txt”
读节点时;做
#后台运行
(正常运行时间=`ssh-o ConnectTimeout=5$node正常运行时间2>&1`
如果[$?-eq 0];则
echo“$node uptime:$uptime”
其他的
echo“节点$node的连接超时”
fi)&
完成<$nodes
#等待所有作业完成
等待

您想编写一个函数来完成以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
参数告诉parallel一次可以激活多少个作业。

我能够找到它并使它工作

我将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

保留一个计数器并向阵列添加10个IP。当计数达到10时,建立连接,等待连接完成,取消设置阵列,将计数重置为0,重复。是否已安装?(或者你愿意安装它吗?)如果你想和一个函数一起使用parallel,你必须先导出这个函数,“--will-cite”选项有什么作用呢?它说你将在工作中引用parallel:代码的问题是If语句不再工作。它可能需要退出函数,但我不知道如何与每个连接(文件中的行)的check并行。在没有shell函数的情况下,还有其他方法可以并行运行。我推荐以下教程: