作为一名机房运维人员,我开发了一个每日监控服务器运行状态的Python脚本。最初,这个程序依赖IDE环境运行,一旦遇到服务器故障重启,程序就会掉线,必须手动重新启动,这在无人值守的机房环境中是不可接受的。为了解决这个问题,我将程序打包为独立可执行文件,并配置了开机自启。本文将分享完整的实践经验。
一、打包方案选型
Python打包工具有多种选择,但针对服务器监控场景,我推荐使用PyInstaller,原因如下:
- 生成单文件可执行程序(–onefile),便于部署
- 支持无控制台窗口运行(–noconsole),适合后台服务
- 跨平台兼容,Windows/Linux均可使用
pip install pyinstaller
二、监控程序代码示例
以下是一个简化版的服务器监控程序,包含日志记录和异常处理机制:
import time
import psutil
import logging
from datetime import datetime
import smtplib
from email.mime.text import MIMEText
# 配置日志(关键:必须使用绝对路径)
log_path = r"C:\\ServerMonitor\\logs\\monitor.log"
logging.basicConfig(
filename=log_path,
level=logging.INFO,
format='%(asctime)s – %(levelname)s – %(message)s'
)
def check_server_status():
"""检查服务器关键指标"""
cpu_percent = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
disk = psutil.disk_usage('/')
status = f"CPU: {cpu_percent}%, 内存: {memory.percent}%, 磁盘: {disk.percent}%"
logging.info(status)
# 告警逻辑
if cpu_percent > 90 or memory.percent > 90:
send_alert(f"服务器资源告急: {status}")
def send_alert(message):
"""发送告警邮件(示例)"""
logging.warning(f"发送告警: {message}")
# 实际邮件发送逻辑…
def main():
logging.info("监控系统启动")
while True:
try:
check_server_status()
time.sleep(300) # 每5分钟检查一次
except Exception as e:
logging.error(f"监控异常: {str(e)}")
time.sleep(60) # 异常后等待1分钟重试
if __name__ == "__main__":
main()
注意事项:服务器程序必须使用绝对路径写入日志,否则打包后可能因找不到路径而失败。
三、PyInstaller打包实战
1. 基础打包命令
pyinstaller –onefile –noconsole server_monitor.py –name ServerMonitor
参数说明:
- –onefile:打包为单文件,便于分发
- –noconsole:关键参数,运行时不显示控制台窗口(适合后台服务)
- –name:指定生成的可执行文件名
2. 处理隐藏导入
如果你的程序使用了psutil等二进制依赖库,可能需要显式声明隐藏导入:
pyinstaller –onefile –noconsole ^
–hidden-import=psutil ^
–hidden-import=smtplib ^
server_monitor.py
3. 高级配置(.spec文件)
对于复杂项目,建议使用.spec文件进行精细控制:
# ServerMonitor.spec
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(
['server_monitor.py'],
pathex=['C:\\\\ServerMonitor'],
binaries=[],
datas=[('config.ini', '.')], # 打包配置文件
hiddenimports=['psutil', 'smtplib'],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='ServerMonitor',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=False, # 无窗口模式
disable_windowed_traceback=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)
修改后使用命令:
pyinstaller ServerMonitor.spec
四、配置开机自启
打包后的可执行文件路径为:dist/ServerMonitor.exe(Windows)或 dist/ServerMonitor(Linux)。
Windows方案:任务计划程序(推荐)
相比注册表,任务计划程序更稳定,支持失效重试:
创建基本任务:
- 名称:ServerMonitor
- 触发器:当特定用户登录时 / 启动时
- 操作:启动程序 C:\\ServerMonitor\\dist\\ServerMonitor.exe
- 起始于:C:\\ServerMonitor\\dist(工作目录很重要)
关键设置:
- 勾选**“不管用户是否登录都要运行”**
- 勾选**“使用最高权限运行”**(监控程序常需管理员权限)
- 在"设置"选项卡中,勾选**“如果任务失败,按以下频率重新启动”**(建议间隔1分钟,尝试3次)
电源设置: 取消勾选**“只有在计算机使用交流电源时才启动”**,避免UPS切换时服务中断。
Linux方案:Systemd服务
创建服务文件 /etc/systemd/system/server-monitor.service:
[Unit]
Description=Server Status Monitor
After=network.target
[Service]
Type=simple
ExecStart=/opt/server_monitor/dist/ServerMonitor
Restart=always
RestartSec=10
User=root
StandardOutput=append:/var/log/server_monitor.log
StandardError=append:/var/log/server_monitor_error.log
[Install]
WantedBy=multi-user.target
启用命令:
sudo systemctl daemon-reload
sudo systemctl enable server-monitor
sudo systemctl start server-monitor
五、运维优化建议
日志轮转:长期运行的监控程序需配置日志切割,防止磁盘占满。Windows可用rotatingfilehandler,Linux推荐logrotate。
心跳检测:在监控程序中加入HTTP接口或定期写入心跳文件,配合外部看门狗程序检测僵死状态。
配置外部化:将告警阈值、邮箱配置等存入独立配置文件,避免每次修改都要重新打包。
静默升级:设计热更新机制,检测到新版本时自动下载替换,并通过计划任务重启服务。
通过以上实践,我的机房监控程序已稳定运行半年,经历了多次服务器重启和断电保护切换,均能实现自动恢复。从IDE里的脚本到工业级的守护进程,PyInstaller和系统服务的结合为Python程序提供了企业级的部署方案。
网硕互联帮助中心






评论前必须登录!
注册