script to read a file with IP addresses and login

梦想与她 提交于 2021-02-11 18:14:43

问题


I have a file named "host.txt" with listing IP addresses of two systems.

~] cat hosts.txt
10.1.1.10
10.1.1.20

Using below script I am trying to login to each system, check status of a service and print the output of each system. The script prompts to login, however does not continue to execute the /opt/agent.sh status command. Can someone please help fix this script?

#!/bin/bash
for HOST in `cat hosts.txt`
do
ssh root@$HOST
STATUS=`/opt/agent.sh status | awk 'NR==1{print $3 $4}'`
echo $STATUS

if [ $STATUS! == "isrunning" ]; then
echo "$host == FAIL"
else
echo "$host == PASS"
fi

回答1:


You script does not continue until the ssh command completes, which does not happen the interactive shell on $HOST that you started with ssh exits. Instead, you want to execute a script on $HOST.

(Also, note the correct way to iterate over the contents of hosts.txt.)

#!/bin/bash
while read HOST; do
do
  if ssh root@$HOST '
      STATUS=`/opt/agent.sh status | awk 'NR==1{print $3 $4}'`
      [ "$STATUS" = "isrunning" ]
   '; then
       echo "$HOST == FAIL"
  else
       echo "$HOST == PASS"
  fi
done < hosts.txt

The remote script simply exits with the result of comparing $STATUS to "isrunning". An if statement on the local host outputs a string based on the that result (which is the result of the ssh command itself). This saves the trouble of having to pass the value of $HOST to the remote host, simplifying the quoting required for the remote script.



来源:https://stackoverflow.com/questions/22201911/script-to-read-a-file-with-ip-addresses-and-login

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!