本文目录导读:

Linux 环境
使用 systemctl(Systemd 系统)
#!/bin/bash
SERVICE_NAME="nginx"
if systemctl is-active --quiet $SERVICE_NAME; then
echo "$SERVICE_NAME 服务运行中"
else
echo "$SERVICE_NAME 服务未运行"
fi
使用 service 命令(SysV init)
#!/bin/bash
SERVICE_NAME="sshd"
if service $SERVICE_NAME status > /dev/null 2>&1; then
echo "$SERVICE_NAME 服务状态正常"
else
echo "$SERVICE_NAME 服务异常"
fi
使用 pgrep 或 pidof(进程检测)
#!/bin/bash
PROCESS_NAME="httpd"
if pgrep -x $PROCESS_NAME > /dev/null; then
echo "$PROCESS_NAME 进程存在"
else
echo "$PROCESS_NAME 进程不存在"
fi
端口检测(服务监听检测)
#!/bin/bash
PORT=3306
if ss -tlnp | grep -q ":$PORT "; then
echo "端口 $PORT 正在监听"
else
echo "端口 $PORT 未监听"
fi
Windows 环境
PowerShell 脚本
# 检测服务状态
$serviceName = "MySQL"
$service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
if ($service -and $service.Status -eq 'Running') {
Write-Host "$serviceName 服务正在运行"
} else {
Write-Host "$serviceName 服务未运行"
}
检测服务是否启动成功
$serviceName = "W3SVC"
$status = (Get-Service $serviceName).Status
switch ($status) {
'Running' { Write-Host "服务正常运行" -ForegroundColor Green }
'Stopped' { Write-Host "服务已停止" -ForegroundColor Red }
'Paused' { Write-Host "服务已暂停" -ForegroundColor Yellow }
default { Write-Host "未知状态: $status" -ForegroundColor Gray }
}
跨平台脚本(Python)
import subprocess
import sys
def check_service_status(service_name):
"""检测服务状态"""
system = sys.platform
if system == "linux" or system == "linux2":
# Linux 系统
cmd = f"systemctl is-active {service_name}"
result = subprocess.run(cmd, shell=True, capture_output=True)
return result.returncode == 0
elif system == "win32":
# Windows 系统
cmd = f"sc query {service_name}"
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return "RUNNING" in result.stdout
else:
raise NotImplementedError(f"不支持的系统: {system}")
# 使用示例
if __name__ == "__main__":
service = "nginx" if sys.platform.startswith("linux") else "nginx"
if check_service_status(service):
print(f"{service} 服务正在运行")
else:
print(f"{service} 服务未运行")
综合检测脚本(Bash)
#!/bin/bash
# 检测指定服务状态,支持多种方式
check_service_status() {
local service_name=$1
# 方法1: 使用 systemctl
if command -v systemctl &> /dev/null; then
if systemctl is-active --quiet $service_name; then
return 0
fi
fi
# 方法2: 使用 service 命令
if command -v service &> /dev/null; then
if service $service_name status &> /dev/null; then
return 0
fi
fi
# 方法3: 检测对应进程
if pgrep -x $service_name > /dev/null 2>&1; then
return 0
fi
return 1
}
# 主程序
SERVICE="apache2"
if check_service_status $SERVICE; then
echo "✓ $SERVICE 服务运行正常"
else
echo "✗ $SERVICE 服务异常,正在尝试重启..."
# 可以在这里添加重启逻辑
fi
注意事项
- 权限问题:检测系统服务通常需要适当权限
- 超时处理:长时间卡住的服务检测应设置超时
- 日志记录:建议记录检测结果以便排查
- 错误处理:服务不存在等情况要妥善处理
推荐使用:
- Linux:
systemctl(优先)或pgrep(快速检测) - Windows:
Get-Service(PowerShell) - 跨平台: Python 脚本
根据实际环境选择合适的检测方法,并注意权限和异常处理。