本文目录导读:

- 方案一:Python + cron(Linux/Mac)
- 方案二:Bash + curl
- 方案三:Node.js + node-cron
- 方案四:PowerShell + Task Scheduler(Windows)
- 方案五:Docker容器化部署
- 配置建议
Python + cron(Linux/Mac)
# status_sender.py
import requests
import json
from datetime import datetime
def send_status():
# 获取当前状态
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
status_data = {
"time": current_time,
"status": "running",
"cpu_usage": 45.2,
"memory_usage": 60.8
}
# 发送到API端点
url = "https://your-api-endpoint.com/status"
headers = {"Content-Type": "application/json"}
try:
response = requests.post(url, json=status_data, headers=headers)
print(f"Status sent: {response.status_code}")
except Exception as e:
print(f"Error sending status: {e}")
if __name__ == "__main__":
send_status()
crontab配置(每30分钟执行):
*/30 * * * * /usr/bin/python3 /path/to/status_sender.py
Bash + curl
#!/bin/bash
# status_sender.sh
# 收集系统状态
HOSTNAME=$(hostname)
TIMESTAMP=$(date +"%Y-%m-%d %H:%M:%S")
CPU_LOAD=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}')
MEM_USAGE=$(free | grep Mem | awk '{print $3/$2 * 100.0}')
# 构建JSON数据
JSON_DATA="{\"hostname\":\"$HOSTNAME\",\"timestamp\":\"$TIMESTAMP\",\"cpu\":$CPU_LOAD,\"memory\":$MEM_USAGE}"
# 发送HTTP请求
curl -X POST https://your-api-endpoint.com/status \
-H "Content-Type: application/json" \
-d "$JSON_DATA"
echo "Status sent at $TIMESTAMP"
使用systemd timer(Linux):
# /etc/systemd/system/status-sender.service [Unit] Description=Status Sender Service [Service] Type=oneshot ExecStart=/usr/local/bin/status_sender.sh # /etc/systemd/system/status-sender.timer [Unit] Description=Run status sender every 30 minutes [Timer] OnCalendar=*:0/30 Persistent=true [Install] WantedBy=timers.target
Node.js + node-cron
// status_sender.js
const cron = require('node-cron');
const axios = require('axios');
const os = require('os');
// 每30分钟执行一次
cron.schedule('*/30 * * * *', async () => {
const status = {
hostname: os.hostname(),
timestamp: new Date().toISOString(),
uptime: os.uptime(),
memory: {
free: os.freemem(),
total: os.totalmem(),
usage_percent: ((os.totalmem() - os.freemem()) / os.totalmem() * 100).toFixed(2)
},
cpu: os.loadavg()[0]
};
try {
const response = await axios.post('https://your-api-endpoint.com/status', status);
console.log('Status sent successfully:', response.data);
} catch (error) {
console.error('Error sending status:', error.message);
}
});
console.log('Status sender started...');
PowerShell + Task Scheduler(Windows)
# status_sender.ps1
param(
[string]$ApiUrl = "https://your-api-endpoint.com/status"
)
$status = @{
timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
computerName = $env:COMPUTERNAME
cpuUsage = (Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average
memoryUsage = (Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory
diskFree = (Get-PSDrive C | Select-Object Free).Free / 1GB
}
$jsonBody = $status | ConvertTo-Json
try {
Invoke-RestMethod -Uri $ApiUrl -Method Post -Body $jsonBody -ContentType "application/json"
Write-Host "Status sent successfully"
} catch {
Write-Error "Failed to send status: $_"
}
Task Scheduler配置:
- 打开Task Scheduler
- 创建基本任务
- 设置触发器(每30分钟)
- 操作:启动PowerShell,参数:
-File "C:\scripts\status_sender.ps1"
Docker容器化部署
# Dockerfile FROM python:3.9-slim WORKDIR /app COPY status_sender.py . COPY requirements.txt . RUN pip install -r requirements.txt # 安装cron RUN apt-get update && apt-get -y install cron # 添加cron任务 RUN echo "*/30 * * * * python /app/status_sender.py >> /var/log/status.log 2>&1" > /etc/cron.d/status-cron RUN chmod 0644 /etc/cron.d/status-cron RUN crontab /etc/cron.d/status-cron CMD ["cron", "-f"]
配置建议
- 错误处理:添加重试机制和日志记录
- 认证:如果API需要认证,添加token/API key
- 配置管理:使用环境变量或配置文件存储敏感信息
- 监控:添加健康检查和告警机制
- 版本控制:将脚本放在Git仓库中管理
您需要哪种实现的具体帮助?请告诉我您的环境和使用场景。