Ubuntu系统上的Python自动化运维可以通过多种方式实现,以下是一些常见的方法和步骤:
my_project_env
的虚拟环境,并指定所需的Python版本(以3.8为例):conda create --name my_project_env python=3.8
conda activate my_project_env
requirements.txt
文件列出了所有依赖:pip install -r requirements.txt
cd /path/to/project_directory
python your_script.py
my_service.service
的服务文件,并放置在/etc/systemd/system/
目录下。文件内容应如下所示(替换相应字段为您的实际信息):[Unit]
Description=My Python Service
After=network.target
[Service]
User=your_username
ExecStart=/home/your_username/miniconda3/envs/my_project_env/bin/python /path/to/your_script.py
Restart=always
RestartSec=10
Environment="PATH=/home/your_username/miniconda3/envs/my_project_env/bin/:$PATH"
[Install]
WantedBy=multi-user.target
启用并启动服务:sudo systemctl enable my_service.service
sudo systemctl start my_service.service
检查服务状态:sudo systemctl status my_service.service
pip install fabric
from fabric import Connection
conn = Connection(host='your_server_ip', user='your_username', connect_kwargs={"password": "your_password"})
result = conn.run('whoami')
print(f"当前登录用户: {result.stdout.strip()}")
from fabric import task
@task
def update_system(c):
"""自动更新系统(适合Ubuntu/Debian)"""
c.run('sudo apt update')
c.run('sudo apt upgrade -y')
c.run('sudo apt autoremove -y')
print("系统更新完成!")
# 在命令行运行
fab -H server1,server2,server3 update_system
def deploy_website(c):
# 创建项目目录
c.run('mkdir -p /var/www/my_site')
# 上传整个文件夹
c.put('local/path/*', '/var/www/my_site/')
# 设置权限
c.run('chmod -R 755 /var/www/my_site')
print("网站部署完成!")
from fabric import Connection
from paramiko import SSHException
try:
with Connection('bad_server') as c:
c.run('lsb_release -a')
except SSHException as e:
print(f"连接失败: {str(e)}")
except Exception as e:
print(f"其他错误: {str(e)}")
import psutil
import smtplib
from email.mime.text import MIMEText
cpu_usage = psutil.cpu_percent(interval=1)
memory_info = psutil.virtual_memory()
memory_usage = memory_info.percent
if cpu_usage > 80 or memory_usage > 80:
msg = MIMEText(f"警告!CPU使用率: {cpu_usage}%,内存使用率: {memory_usage}%")
msg['Subject'] = '服务器性能警告'
msg['From'] = 'your_email@example.com'
msg['To'] = 'alert_recipient@example.com'
with smtplib.SMTP('smtp.example.com') as server:
server.send_message(msg)
automation.py
,并编写代码来实现自动化任务,如批量处理文件、监控系统状态、自动部署应用等。crontab -e
添加一行来设置定时任务,例如每天凌晨1点执行脚本:0 1 * * * /home/user/scripts/my_script.py
通过以上步骤,您可以在Ubuntu系统上实现Python自动化运维,提高运维效率,减少人为错误。