ubuntu

Ubuntu上Python自动化运维如何操作

小樊
49
2025-07-19 18:48:05
栏目: 编程语言

在Ubuntu上实现Python自动化运维可以通过多种方法和工具来完成,以下是一些常见的方法和步骤:

配置Python环境

sudo apt update
sudo apt install python3 python3-pip
python3 -m venv my_project_env
source my_project_env/bin/activate
pip install -r requirements.txt

编写自动化脚本

import subprocess

def check_service(service_name):
    result = subprocess.run(['sudo', 'systemctl', 'is-active', service_name], capture_output=True, text=True)
    if result.stdout.strip() != 'active':
        subprocess.run(['sudo', 'systemctl', 'restart', service_name])

if __name__ == "__main__":
    check_service('nginx')

设置开机自启动

sudo nano /etc/systemd/system/my_service.service

文件内容示例:

[Unit]
Description=My Python Service
After=network.target

[Service]
User=your_username
ExecStart=/path/to/your_script.py
Restart=always
RestartSec=10
Environment="PATH=/path/to/your/virtualenv/bin/:$PATH"

[Install]
WantedBy=multi-user.target
sudo systemctl enable my_service.service
sudo systemctl start my_service.service

使用自动化工具

0
看了该问题的人还看了