自动重启服务的脚本代码示例

wen 实用脚本 1

本文目录导读:

自动重启服务的脚本代码示例

  1. Linux Systemd 服务自动重启(推荐)
  2. Linux Shell 脚本监控重启
  3. Python 守护进程自动重启
  4. Docker 容器自动重启
  5. Windows 服务自动重启 PowerShell 脚本
  6. 使用 Supervisord 管理自动重启
  7. 使用建议

Linux Systemd 服务自动重启(推荐)

创建 systemd 服务单元文件

# /etc/systemd/system/myapp.service
[Unit]
Description=My Application Service
After=network.target
[Service]
Type=simple
User=myuser
WorkingDirectory=/opt/myapp
ExecStart=/usr/bin/python3 /opt/myapp/app.py
Restart=always
RestartSec=10
StartLimitInterval=0
StartLimitBurst=5
[Install]
WantedBy=multi-user.target

启用并启动服务

sudo systemctl daemon-reload
sudo systemctl enable myapp.service
sudo systemctl start myapp.service

Linux Shell 脚本监控重启

#!/bin/bash
# 自动重启监控脚本 monitor_restart.sh
SERVICE_NAME="myapp"
SERVICE_CMD="/usr/bin/python3 /opt/myapp/app.py"
LOG_FILE="/var/log/restart_monitor.log"
MAX_RESTARTS=10
RESTART_INTERVAL=60  # 重启间隔(秒)
restart_count=0
while true; do
    # 检查服务是否运行
    if ! pgrep -f "$SERVICE_NAME" > /dev/null; then
        echo "$(date) - $SERVICE_NAME is down. Attempting restart..." >> "$LOG_FILE"
        # 检查重启次数限制
        if [ $restart_count -ge $MAX_RESTARTS ]; then
            echo "$(date) - Max restarts ($MAX_RESTARTS) reached. Not restarting." >> "$LOG_FILE"
            break
        fi
        # 重启服务
        $SERVICE_CMD &
        PID=$!
        echo "$(date) - Service restarted with PID $PID" >> "$LOG_FILE"
        ((restart_count++))
        # 等待一段时间再检查
        sleep $RESTART_INTERVAL
    fi
    sleep 5
done

使用方式

chmod +x monitor_restart.sh
nohup ./monitor_restart.sh &

Python 守护进程自动重启

#!/usr/bin/env python3
"""
自动重启服务的 Python 脚本 auto_restart.py
"""
import subprocess
import time
import sys
import os
from datetime import datetime
class ServiceRestarter:
    def __init__(self, service_command, service_name=None, 
                 max_restarts=10, restart_delay=10):
        self.service_command = service_command
        self.service_name = service_name or service_command.split('/')[-1]
        self.max_restarts = max_restarts
        self.restart_delay = restart_delay
        self.restart_count = 0
        self.log_file = f"/var/log/{self.service_name}_restart.log"
    def log_message(self, message):
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_entry = f"[{timestamp}] {message}"
        print(log_entry)
        # 写入日志文件
        with open(self.log_file, 'a') as f:
            f.write(log_entry + "\n")
    def is_running(self):
        """检查服务是否在运行"""
        try:
            result = subprocess.run(
                ["pgrep", "-f", self.service_name],
                capture_output=True,
                text=True
            )
            return result.returncode == 0
        except:
            return False
    def start_service(self):
        """启动服务"""
        try:
            process = subprocess.Popen(
                self.service_command.split(),
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            self.log_message(f"Service started with PID: {process.pid}")
            return process.pid
        except Exception as e:
            self.log_message(f"Failed to start service: {e}")
            return None
    def run(self):
        """主循环"""
        self.log_message(f"Starting monitor for: {self.service_name}")
        while self.restart_count < self.max_restarts:
            if not self.is_running():
                self.restart_count += 1
                self.log_message(
                    f"Service not running. Attempt {self.restart_count}/{self.max_restarts}"
                )
                pid = self.start_service()
                if pid:
                    self.log_message(f"Restart successful (PID: {pid})")
                    # 等待一段时间再检查
                    time.sleep(self.restart_delay)
                else:
                    self.log_message("Restart failed")
                    time.sleep(5)
            else:
                self.log_message("Service is running")
            time.sleep(10)  # 检查间隔
        self.log_message("Maximum restart attempts reached. Exiting.")
if __name__ == "__main__":
    # 配置参数
    service_cmd = "/usr/bin/python3 /opt/myapp/app.py"
    restarter = ServiceRestarter(
        service_command=service_cmd,
        service_name="myapp",
        max_restarts=5,
        restart_delay=10
    )
    restarter.run()

Docker 容器自动重启

使用 Docker Compose 自动重启

# docker-compose.yml
version: '3.8'
services:
  myapp:
    image: myapp:latest
    restart: always
    restart_policy:
      condition: on-failure
      max_attempts: 5
      wait: 10s
    ports:
      - "8080:8080"
    environment:
      - NODE_ENV=production

使用 Docker Run 命令

docker run -d \
  --name myapp \
  --restart=always \
  --restart-max-attempts=5 \
  --restart-window=10s \
  myapp:latest

Windows 服务自动重启 PowerShell 脚本

# auto_restart.ps1
$serviceName = "MyAppService"
$maxRestarts = 10
$restartCount = 0
$logFile = "C:\logs\restart_log.txt"
function Write-Log {
    param($message)
    $timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $logEntry = "[$timestamp] $message"
    Write-Host $logEntry
    Add-Content -Path $logFile -Value $logEntry
}
while ($restartCount -lt $maxRestarts) {
    $service = Get-Service -Name $serviceName -ErrorAction SilentlyContinue
    if ($service.Status -ne "Running") {
        $restartCount++
        Write-Log "Service '$serviceName' is stopped. Restart attempt $restartCount/$maxRestarts"
        try {
            Start-Service -Name $serviceName
            Write-Log "Service '$serviceName' started successfully"
            Start-Sleep -Seconds 10  # Wait 10 seconds before next check
        }
        catch {
            Write-Log "Failed to start service: $_"
        }
    }
    else {
        Write-Log "Service '$serviceName' is running"
    }
    Start-Sleep -Seconds 30  # Check every 30 seconds
}
Write-Log "Maximum restart attempts reached. Exiting."

设置定时任务自动执行

# 创建计划任务每小时执行一次
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" `
    -Argument "-File C:\scripts\auto_restart.ps1"
$trigger = New-ScheduledTaskTrigger -Daily -At "00:00" `
    -RepetitionInterval (New-TimeSpan -Hours 1) `
    -RepetitionDuration (New-TimeSpan -Days 365)
Register-ScheduledTask -TaskName "ServiceAutoRestart" `
    -Action $action -Trigger $trigger -RunLevel Highest

使用 Supervisord 管理自动重启

安装并配置 Supervisord

# 安装 supervisord
sudo apt-get install supervisor
# 创建配置文件 /etc/supervisor/conf.d/myapp.conf
[program:myapp]
command=/usr/bin/python3 /opt/myapp/app.py
directory=/opt/myapp
user=myuser
autostart=true
autorestart=true
startretries=10
exitcodes=0
stopsignal=TERM
stopwaitsecs=10
stdout_logfile=/var/log/myapp_stdout.log
stderr_logfile=/var/log/myapp_stderr.log

管理 Supervisord 服务

# 更新配置
sudo supervisorctl reread
sudo supervisorctl update
# 管理服务
sudo supervisorctl start myapp
sudo supervisorctl stop myapp
sudo supervisorctl restart myapp
sudo supervisorctl status myapp

使用建议

  1. 选择合适方案

    • Linux 服务:优先使用 systemd 或 supervisord
    • Docker 环境:使用 Docker 内置重启策略
    • Windows 服务:使用 Service 属性或计划任务
  2. 配置日志记录:记录重启事件和原因,便于故障排查

  3. 限制重启次数:避免无限重启导致的资源浪费

  4. 设置合理间隔:至少等待 5-10 秒再尝试重启

  5. 监控通知:重要服务建议配合监控告警系统

  6. 测试环境验证:先在测试环境验证重启逻辑

抱歉,评论功能暂时关闭!