Ubuntu进程自动化运维实践
定时任务是Ubuntu中最基础的自动化手段,适用于周期性执行的进程(如日志清理、数据备份)。常用工具包括cron和anacron:
crontab -e编辑当前用户的定时任务,语法格式为分钟 小时 日期 月份 星期 命令。例如,每天凌晨1点清理/tmp目录下超过7天的临时文件,可添加:0 1 * * * find /tmp -type f -mtime +7 -delete。/etc/anacrontab,例如每天执行/home/user/backup.sh,可添加:1 5 backup-job /home/user/backup.sh(1表示间隔1天,5表示延迟5分钟执行)。Systemd是Ubuntu的默认服务管理器,适合需要常驻后台、自动重启的进程(如Web服务、数据库)。通过创建自定义服务单元文件,可实现进程的自动化启动、停止和重启:
/etc/systemd/system/下新建.service文件(如my_process.service),内容模板如下:[Unit]
Description=My Custom Process
After=network.target # 依赖网络服务启动
[Service]
ExecStart=/usr/local/bin/my_process.sh # 进程启动命令
Restart=always # 进程崩溃时自动重启
User=ubuntu # 以指定用户身份运行
WorkingDirectory=/usr/local/bin # 工作目录
[Install]
WantedBy=multi-user.target # 系统多用户模式启动时加载
sudo systemctl enable my_process.service(设置开机自启),sudo systemctl start my_process.service(立即启动)。通过systemctl status my_process.service可查看服务状态。为避免进程意外崩溃导致业务中断,需结合监控工具实现自动检测与恢复:
/etc/supervisor/conf.d/(如my_process.conf),内容示例:[program:my_process]
command=/usr/local/bin/my_process.sh # 进程命令
directory=/usr/local/bin # 工作目录
user=ubuntu # 运行用户
autostart=true # 开机自启
autorestart=true # 崩溃时自动重启
stderr_logfile=/var/log/my_process.err.log # 错误日志路径
stdout_logfile=/var/log/my_process.out.log # 输出日志路径
执行sudo supervisorctl reread(加载新配置)、sudo supervisorctl update(更新进程列表)、sudo supervisorctl start my_process(启动进程)即可生效。/etc/monit/monitrc,例如监控Nginx进程:check process nginx with pidfile /var/run/nginx.pid
start program = "/etc/init.d/nginx start"
stop program = "/etc/init.d/nginx stop"
if failed host 127.0.0.1 port 80 protocol http then restart
if 5 restarts within 5 cycles then timeout
执行sudo monit reload加载配置后,Monit会自动监控Nginx进程,若端口80无响应则重启服务。通过Shell脚本封装重复性操作,可实现批量进程管理、日志分析、系统维护等自动化任务。常见脚本示例:
python进程):#!/bin/bash
pkill -9 -f "python.*test_script.py" # 终止包含"test_script.py"的python进程
echo "异常Python进程已清理"
#!/bin/bash
if ! systemctl is-active --quiet nginx; then
systemctl restart nginx
echo "$(date): Nginx已重启" >> /var/log/service_monitor.log
fi
if ! systemctl is-active --quiet mysql; then
systemctl restart mysql
echo "$(date): MySQL已重启" >> /var/log/service_monitor.log
fi
将脚本添加到cron中(如每5分钟执行一次),可实现服务的持续监控。- hosts: webservers
become: true
tasks:
- name: Ensure Nginx is installed
apt:
name: nginx
state: present
- name: Start Nginx service
service:
name: nginx
state: started
enabled: true
执行ansible-playbook playbook.yml即可完成批量操作。