是否有一种简单的方法可以从控制台检查Internet连接?我正在尝试在shell脚本中玩耍。我看来的一个想法是wget -spider http://www.google.com/并检查HTTP响应代码以解释Internet连接是否正常。
这是我正在尝试的:
#!/bin/bash
# Sending the output of the wget in a variable and not what wget fetches
RESULT=`wget --spider http://google.com 2>&1`
FLAG=0
# Traverse the string considering it as an array of words
for x in $RESULT; do
if [ "$x" = '200' ]; then
FLAG=1 # This means all good
fi
done
有什么办法可以实现这一目标?
您可以使用ping
或curl
命令进行操作。检查man
以了解更多。
我自己正在使用它,有点对我有用!它从可靠的网站(例如Google(检查连接,如果它获得200
状态作为响应,您可能有Internet。
if curl -s --head --request GET www.google.com | grep "200 OK" > /dev/null ; then
echo "Internet is present"
else
echo "Internet isn't present"
fi
在一行,谢谢@ps
if ping -c1 8.8.8.8 &>/dev/null ;then echo Working ;else echo Down ;fi
一个不使用Internet查看是否可用的选项是检查路由表中的默认路由。路由守护程序将在不可用时删除您的默认路由,并在它时添加回去。
netstat -nrf inet | grep -q ^default &&
echo internet is up ||
echo internet is down
要检查网站是否已启动,您可以使用NetCat查看它是否在端口80上收听。这有助于拒绝使用" 405方法"拒绝头部请求的网站。
nc -zw2 www.example.com 80 &>/dev/null &&
echo website is up ||
echo website is down
请尝试此代码。
#!/bin/bash
wget -q --spider http://google.com
if [ $? -eq 0 ]; then
echo "Internet connection is OK"
else
echo "Internet connection is FAILED"
fi
@carlos-abraham答案的更紧凑的变体。您可以让curl
仅输出HTTP响应代码,然后对其做出决定
# 200 if everything is ok
http_code=$(curl -s --head -m 5 -w %{http_code} --output /dev/null www.google.com)
if [ "$http_code" -eq 200 ]; then
echo "success"
else
# write error to stderr
echo "http request failed: $http_code" >&2
exit 1
fi
-m 5
:等待整个操作5秒
--output /dev/null
:抑制HTML站点响应
-w %{http_code}
:写入http响应代码。
更多的详细脚本以检查连接性和HTTP响应
#url="mmm.elgoog.moc"
url="www.google.com"
max_wait=5
(ping -w $max_wait -q -c 1 "$url" > /dev/null 2>&1 )
response_code=$?
if [ "$response_code" -eq 0 ]; then
# 200 if everything is ok
response_code=$(curl -s --head -m $max_wait -w %{http_code} --output /dev/null "$url")
fi
case "$response_code" in
1)
echo "Connectivity failed. Host down?" >&2
exit $response_code
;;
2)
echo "Unknown host or other problem. DNS problem?" >&2
exit $response_code
;;
200)
echo "success"
exit 0
;;
*)
echo "Failed to get a response: $response_code" >&2
exit 1
esac