shell检查主机是否alive
使用ping检测网络是否通
ping是检查主机是否alive的方法,加上参数可以只ping一次,并等待1秒:
if ping -c 1 -W 1 "$hostname_or_ip_address"; then
echo "$hostname_or_ip_address is alive"
else
echo "$hostname_or_ip_address is pining for the fjords"
fi#!/bin/bash
ping -q -w1 -c1 google.com &>/dev/null && echo online || echo offlineping默认网关检测
#!/bin/bash
ping -q -w 1 -c 1 `ip r | grep default | cut -d ' ' -f 3` > /dev/null && echo ok || echo error使用wget
#!/bin/bash
wget -q --spider http://google.com
if [ $? -eq 0 ]; then
echo "Online"
else
echo "Offline"
fi这里 -q 蚕食是Silence模式;--spider表示不是实际下载,而只是检测页面是否存在
使用nc检测端口
如果检查端口可参考 Test if remote TCP port is open from a shell script
此外,交互检查(设置5秒超时):
同样,返回值0表示成功,1表示失败
以下是案例脚本
也可以使用telnet来检查端口,但是要解决telnet超时问题(需要使用timeout命令):
以下是一个巧妙的检查端口脚本方法,并且使用了timeout来限制超时:
参考
Last updated
Was this helpful?