脚本以读取具有IP地址并登录的文件 [英] script to read a file with IP addresses and login

查看:67
本文介绍了脚本以读取具有IP地址并登录的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为"host.txt"的文件,其中列出了两个系统的IP地址.

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

使用以下脚本,我试图登录到每个系统,检查服务状态并打印每个系统的输出.该脚本提示登录,但是不会继续执行/opt/agent.sh status命令.有人可以帮忙解决此脚本吗?

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

推荐答案

ssh 命令完成之前,脚本不会继续执行,这不会在 $ HOST 上进行交互式shell处理.您以 ssh 开头的code>退出.相反,您想在 $ HOST 上执行脚本.

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.

(此外,请注意迭代 hosts.txt 的内容的正确方法.)

(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

远程脚本只是退出,其结果是将 $ STATUS 与正在运行"进行比较.本地主机上的 if 语句基于该结果输出字符串(这是 ssh 命令本身的结果).这样省去了将 $ HOST 的值传递给远程主机的麻烦,简化了远程脚本所需的引用.

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.

这篇关于脚本以读取具有IP地址并登录的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆