本文目录导读:

- 使用 Python (requests 库)
- 使用 Bash + curl (Linux/Mac)
- 使用 Node.js (JavaScript)
- 使用 PowerShell (Windows)
- 进阶检测 (Python 完整版)
- 关键检测指标说明
- 实用技巧
使用 Python (requests 库)
import requests
from requests.exceptions import RequestException
def check_website_status(url, timeout=10):
try:
response = requests.get(url, timeout=timeout)
# 检查 HTTP 状态码
if response.status_code == 200:
return True, f"网站正常 (状态码: 200)"
else:
return False, f"异常状态码: {response.status_code}"
except requests.ConnectionError:
return False, "无法连接 - 网络问题或域名不存在"
except requests.Timeout:
return False, "请求超时"
except RequestException as e:
return False, f"请求异常: {str(e)}"
# 使用示例
status, message = check_website_status("https://www.example.com")
print(f"状态: {status}, 信息: {message}")
使用 Bash + curl (Linux/Mac)
#!/bin/bash
check_site() {
local url=$1
local timeout=$2
# 使用 curl 检测 HTTP 状态码
response=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout $timeout $url)
if [ $? -ne 0 ]; then
echo "❌ 无法连接: $url"
return 1
fi
if [ "$response" -eq 200 ] || [ "$response" -eq 301 ] || [ "$response" -eq 302 ]; then
echo "✅ 网站正常: $url (状态码: $response)"
return 0
else
echo "❌ 异常状态: $url (状态码: $response)"
return 1
fi
}
# 批量检测
sites=("https://www.google.com" "https://www.github.com" "https://www.example.com")
for site in "${sites[@]}"; do
check_site $site 5
done
使用 Node.js (JavaScript)
const https = require('https');
const http = require('http');
function checkWebsiteStatus(url, timeout = 10000) {
return new Promise((resolve, reject) => {
const protocol = url.startsWith('https') ? https : http;
const req = protocol.get(url, { timeout }, (res) => {
const statusCode = res.statusCode;
if (statusCode >= 200 && statusCode < 400) {
resolve({
status: 'up',
code: statusCode,
message: `网站正常 (状态码: ${statusCode})`
});
} else {
resolve({
status: 'down',
code: statusCode,
message: `异常状态码: ${statusCode}`
});
}
});
req.on('error', (err) => {
resolve({
status: 'down',
code: 0,
message: `连接失败: ${err.message}`
});
});
req.on('timeout', () => {
req.destroy();
resolve({
status: 'down',
code: 0,
message: '请求超时'
});
});
});
}
// 使用示例 (异步)
async function main() {
const result = await checkWebsiteStatus('https://www.example.com');
console.log(`状态: ${result.status}, 信息: ${result.message}`);
}
main();
使用 PowerShell (Windows)
function Check-WebsiteStatus {
param(
[string]$Url,
[int]$TimeoutSeconds = 10
)
try {
$request = [System.Net.WebRequest]::Create($Url)
$request.Timeout = $TimeoutSeconds * 1000
$request.Method = "HEAD" # 使用 HEAD 请求减少数据量
$response = $request.GetResponse()
$statusCode = [int]$response.StatusCode
if ($statusCode -eq 200) {
Write-Host "✅ 网站正常 ($Url)" -ForegroundColor Green
return $true
} else {
Write-Host "⚠️ 状态码: $statusCode ($Url)" -ForegroundColor Yellow
return $false
}
}
catch {
Write-Host "❌ 连接失败: $($_.Exception.Message)" -ForegroundColor Red
return $false
}
}
# 使用示例
Check-WebsiteStatus -Url "https://www.example.com"
进阶检测 (Python 完整版)
import requests
import time
from concurrent.futures import ThreadPoolExecutor
class WebsiteMonitor:
def __init__(self, urls, timeout=10, max_workers=5):
self.urls = urls
self.timeout = timeout
self.workers = max_workers
def check_single(self, url):
start_time = time.time()
try:
response = requests.get(url, timeout=self.timeout)
response_time = round((time.time() - start_time) * 1000, 2)
return {
'url': url,
'status': 'up' if response.status_code == 200 else 'warning',
'code': response.status_code,
'response_time': f"{response_time}ms",
'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
}
except Exception as e:
return {
'url': url,
'status': 'down',
'code': 0,
'response_time': 'N/A',
'error': str(e),
'timestamp': time.strftime('%Y-%m-%d %H:%M:%S')
}
def check_all(self):
with ThreadPoolExecutor(max_workers=self.workers) as executor:
results = list(executor.map(self.check_single, self.urls))
return results
# 使用示例
monitor = WebsiteMonitor([
'https://www.google.com',
'https://www.github.com',
'https://www.notexist123.com'
])
results = monitor.check_all()
for result in results:
status_icon = "✅" if result['status'] == 'up' else "❌"
print(f"{status_icon} {result['url']} - {result['status']} - {result.get('response_time', 'N/A')}")
关键检测指标说明
| 说明 | 实现方式 |
|---------|------|---------|
| HTTP 状态码 | 200=正常, 4xx=客户端错误, 5xx=服务器错误 | response.status_code |
| 响应时间 | 页面加载速度 | time.time() 计算 |匹配 | 检测页面是否包含特定关键词 | response.text.find('keyword') |
| SSL 证书 | 证书是否过期或有效 | ssl 模块检查 |
| 连通性** | 是否能 Ping 通或连接端口 | ping 命令或 socket |
实用技巧
-
使用 HEAD 请求:减少数据传输,只获取响应头
response = requests.head(url)
-
设置重试机制:避免临时网络波动误判
from requests.adapters import HTTPAdapter session = requests.Session() session.mount('http://', HTTPAdapter(max_retries=3)) -
记录日志:保存检测历史用于分析
import logging logging.basicConfig(filename='website_monitor.log', level=logging.INFO)
-
定时执行:使用 cron (Linux) 或 Task Scheduler (Windows) 定期运行脚本
这些脚本可以根据你的具体需求调整,比如添加邮件通知、生成报表等高级功能。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
足球直播
足球直播
足球直播
篮球直播
篮球直播
篮球直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
亚冠直播
亚冠直播
亚冠直播
欧冠直播
欧冠直播
欧冠直播
英超直播
英超直播
英超直播
西甲直播
西甲直播
西甲直播
中超直播
中超直播
中超直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
曼联直播
曼联直播
曼联直播
日职联直播
日职联直播
日职联直播
澳超直播
澳超直播
澳超直播
阿森纳直播
阿森纳直播
阿森纳直播
足球直播
足球直播
足球直播
NBA直播
NBA直播
NBA直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
欧冠直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播
中超直播