使用bash脚本检查网络中不同计算机的信息

时间:2018-05-14 17:09:16

标签: linux bash

我正在尝试编写一个bash脚本来访问一个文件(nodeNames),该文件包含到群集网络中不同计算机的IP地址,ssh到这些计算机中,并输出一些基本信息,即:Hostname,Host IP地址,平均负载和使用最多内存的进程,并将所有这些信息附加到一个文件中,每个逗号分隔。此外,每台计算机都具有相同的用户名和密码。这是我的代码到目前为止,但它不起作用,请在这里需要帮助

egrep -ve '^#|^$'nodeNames | while read a
do
ssh $a "$@" &
output1=`hostname`

#This will display the server's IP address
output2=`hostname -i`

#This will output the server's load average 
output3=`uptime  | grep -oP '(?<=average:).*'| tr -d ','`

#This outputs memory Information
output4=`ps aux --sort=-%mem | awk 'NR<=1{print $0}'`

#This concantenates all output to a single line of text written to 
echo "$output1, $output2, $output3, $output4" | tee clusterNodeInfo
done

1 个答案:

答案 0 :(得分:0)

您需要了解在哪台计算机上执行的操作。您启动的shell脚本在主机A上执行,并且您需要来自主机B的信息。ssh $a "$@" &不会突然使所有命令在远程主机B上执行。因此,

output1=`hostname`

将在主机A上执行,output1将具有主机A的主机名。

您可能还想将tee置于循环之外或使用tee -a来阻止覆盖输出文件。

对于bash,请使用$()而不是``。

所以,这将使你的脚本:

egrep -ve '^#|^$'nodeNames | while read a
do
    output1=$(ssh $a hostname)

    #This will display the server's IP address
    output2=$(ssh $a hostname -i)

    #This will output the server's load average 
    output3=$(ssh $a "uptime  | grep -oP '(?<=average:).*'| tr -d ','")

    #This outputs memory Information
    output4=$(ssh $a "ps aux --sort=-%mem | awk 'NR<=1{print $0}'")

    #This concantenates all output to a single line of text written to 
    echo "$output1, $output2, $output3, $output4" | tee -a  clusterNodeInfo
done

(尚未测试过,但它应该是这样的)