本文目录导读:

- 使用
ping命令(最常用) - 使用
curl命令(检查HTTP服务) - 使用
wget命令 - 使用
nc(netcat) 命令(检查特定端口) - 使用
timeout+/dev/tcp(纯Shell方式) - 综合检查函数
- 完整脚本示例(带重试机制)
- 选择建议
- 注意事项
在Shell脚本中,有多种检查网络连通性的方法,以下是常见的几种:
使用 ping 命令(最常用)
#!/bin/bash
TARGET="8.8.8.8"
# 发送1个包,超时2秒
if ping -c 1 -W 2 $TARGET &> /dev/null; then
echo "网络连通:$TARGET"
else
echo "网络不通:$TARGET"
fi
参数说明:
-c 1:发送1个包-W 2:超时2秒(Linux)-t 2:超时2秒(macOS/BSD)&> /dev/null:忽略输出
使用 curl 命令(检查HTTP服务)
#!/bin/bash
# 检查是否能访问网站
if curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 http://www.baidu.com | grep -q 200; then
echo "网站可以访问"
else
echo "网站无法访问"
fi
更完整的版本:
#!/bin/bash
check_http() {
local url=$1
local timeout=5
local http_code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout $timeout $url 2>/dev/null)
if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 400 ]; then
return 0 # 成功
else
return 1 # 失败
fi
}
if check_http "https://www.baidu.com"; then
echo "服务正常"
else
echo "服务异常"
fi
使用 wget 命令
#!/bin/bash
if wget -q --spider --timeout=10 http://www.baidu.com 2>/dev/null; then
echo "网络连通"
else
echo "网络不通"
fi
参数说明:
-q:静默模式--spider:不下载文件,只检查链接--timeout=10:超时10秒
使用 nc (netcat) 命令(检查特定端口)
#!/bin/bash
HOST="8.8.8.8"
PORT=53 # DNS端口
if nc -zv -w 5 $HOST $PORT 2>&1 | grep -q succeeded; then
echo "主机 $HOST 的 $PORT 端口可达"
else
echo "主机 $HOST 的 $PORT 端口不可达"
fi
使用 timeout + /dev/tcp(纯Shell方式)
#!/bin/bash
check_tcp() {
local host=$1
local port=$2
local timeout=3
# 使用timeout命令设置超时
timeout $timeout bash -c "echo > /dev/tcp/$host/$port" 2>/dev/null
if [ $? -eq 0 ]; then
echo "连接 $host:$port 成功"
return 0
else
echo "连接 $host:$port 失败"
return 1
fi
}
check_tcp "google.com" 80
综合检查函数
#!/bin/bash
# 检查网络连通性
check_network() {
local targets=("8.8.8.8" "114.114.114.114")
local success=false
for target in "${targets[@]}"; do
if ping -c 1 -W 2 $target &> /dev/null; then
success=true
break
fi
done
if $success; then
echo "网络连通性正常"
return 0
else
echo "网络连接失败"
return 1
fi
}
# 检查特定服务
check_service() {
local host=$1
local port=$2
# 同时ping和端口检查
if ping -c 1 -W 2 $host &> /dev/null; then
if timeout 3 bash -c "echo > /dev/tcp/$host/$port" 2>/dev/null; then
echo "服务 $host:$port 正常运行"
return 0
else
echo "主机可达但端口 $port 未开放"
return 2
fi
else
echo "主机 $host 不可达"
return 1
fi
}
# 使用示例
if check_network; then
check_service "www.baidu.com" 443
fi
完整脚本示例(带重试机制)
#!/bin/bash
# 带重试的网络检查
check_with_retry() {
local target=$1
local max_retries=3
local delay=2
for ((i=1; i<=max_retries; i++)); do
echo "尝试 $i/$max_retries..."
if ping -c 1 -W 3 $target &> /dev/null; then
echo "✓ 网络连通成功"
return 0
fi
if [ $i -lt $max_retries ]; then
echo "等待 ${delay}秒后重试..."
sleep $delay
fi
done
echo "✗ 网络检查失败(已重试 $max_retries 次)"
return 1
}
# 使用
check_with_retry "8.8.8.8"
选择建议
| 场景 | 推荐方法 |
|---|---|
| 基本网络连通性 | ping |
| 检查Web服务 | curl 或 wget |
| 检查特定端口 | nc 或 /dev/tcp |
| 最小化依赖 | /dev/tcp(纯Shell) |
| 生产环境 | 组合多种方法 |
注意事项
- 权限问题:
ping可能需要root权限 - 环境兼容:不同系统命令参数略有差异
- 防火墙:某些环境可能禁止ICMP(ping被屏蔽)
- 性能考虑:设置合适的超时时间,避免脚本卡死
- 可靠性:建议使用多个目标进行冗余检查