如何让这个脚本捕获它返回的错误类型(500,503,402等)并在消息中添加它?
#!/bin/bash
hostlist=(s-example1.us s-example2.us)
for host in "${hostlist[@]}"; do
if nc -w 2 -z $host 80; then
echo "INFO: ssh on $host responding [Looks Good]"
else
echo "ERROR: ssh on $host not responding[Ooops something went wrong]"
fi
done
答案 0 :(得分:0)
您可能希望捕获变量中的输出,然后根据500,503,402的匹配来调整消息:
test=$(nc -w 2 -z $host 80)
if [[ -n $(grep '500\|503\|402' <<< $test) ]]; then
...
else
echo ok
fi
答案 1 :(得分:0)
要检查网站的HTTP状态代码,我建议您使用curl
代替:
#!/bin/bash
hostlist=(s-example1.us s-example2.us)
for host in "${hostlist[@]}"; do
status=$(curl -sLI -o /dev/null -w "%{http_code}" "$host")
case "$status" in
200) echo "INFO: ssh on $host responding [Looks Good]" ;;
*) echo "ERROR: $host responded with $status" ;;
esac
done
答案 2 :(得分:0)
我建议使用cURL。
这样的东西只会为你提供任何端点的状态代码。这将从每个主机输出响应代码,如果响应代码无效(000),它将在另一个消息中返回失败的响应代码。
<强> CODE:强>
#!/bin/bash
hosts=(fliggerfloffin.com google.com)
for host in ${hosts[@]}; do
code=$(curl -m 2 -s -o /dev/null -w "%{http_code}" ${host})
if [[ -z $code ]]; then
printf "%s\n" "Missing response code from host"
exit 1
fi
if (( $code == 000 )); then
code="FAILURE"
fi
printf "%s\n" "HOST: [$host] STATUS: [${code}]"
done
输出:
dumbledore@ansible1a [OPS]:~ > bash test.sh
HOST: [fliggerfloffin.com] STATUS: [FAILURE]
HOST: [google.com] STATUS: [301]