CentOS虚拟机自动化运维实践指南
在CentOS环境中,虚拟机(尤其是KVM-based)的自动化运维可通过脚本工具(Shell/Python)与专业运维工具结合实现,覆盖虚拟机生命周期管理、配置标准化、监控告警等核心场景,提升运维效率与一致性。
Shell脚本是CentOS中最基础的自动化工具,适合执行重复性命令(如系统更新、备份、虚拟机创建)。以下是常见场景示例:
yum命令自动更新所有包、清理缓存,并输出结果提示。#!/bin/bash
# 更新所有包并清理缓存
sudo yum update -y && sudo yum clean all
echo "系统更新与清理完成"
tar压缩备份,并通过cron定时执行(如每天凌晨2点)。#!/bin/bash
SOURCE_DIR="/data/webapps"
BACKUP_DIR="/backup"
DATE=$(date +%Y%m%d%H%M%S)
BACKUP_FILE="$BACKUP_DIR/webapps_$DATE.tar.gz"
mkdir -p $BACKUP_DIR
tar -czvf $BACKUP_FILE $SOURCE_DIR
echo "备份完成: $BACKUP_FILE"
qemu-img创建差异磁盘、virsh复制XML模板并注册虚拟机,实现KVM虚拟机的批量创建(如从base-centos79模板生成centos79-node01、centos79-node02等)。#!/bin/bash
IMG_DIR="/data1/qcow_images"
XML_DIR="/etc/libvirt/qemu"
BASE_VM="base-centos79"
VM_PREFIX="centos79-node"
MAC_PREFIX="52:54:00"
# 创建差异磁盘
qemu-img create -f qcow2 -b "$IMG_DIR/$BASE_VM.qcow2" "$IMG_DIR/${VM_PREFIX}01.qcow2"
# 复制并替换XML模板中的UUID、MAC地址
sed -e "s/$BASE_VM/${VM_PREFIX}01/g" -e "s/<uuid>.*<\/uuid>/<uuid>$(uuidgen)<\/uuid>/" -e "s/<mac address='..:..:..:..:..:..'\/>/<mac address='$MAC_PREFIX:$(tr -dc '0-9a-f' < /dev/urandom | head -c 6 | sed 's/\(..\)/\1:/g;s/:$//')'\/>/" "$XML_DIR/$BASE_VM.xml" > "/tmp/${VM_PREFIX}01.xml"
virsh define "/tmp/${VM_PREFIX}01.xml"
echo "虚拟机 ${VM_PREFIX}01 创建成功"
以上脚本需赋予执行权限(chmod +x script.sh),可通过cron设置定时任务(如0 2 * * * /path/to/backup.sh)实现自动化。
Python通过第三方库(如paramiko、fabric、psutil)实现更复杂的自动化任务,适合需要跨平台、模块化管理的场景:
psutil库采集CPU、内存使用率,超过阈值时发送邮件通知。import psutil
import smtplib
from email.mime.text import MIMEText
def send_alert(subject, message):
sender = "admin@example.com"
receivers = ["devops@example.com"]
msg = MIMEText(message)
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = ", ".join(receivers)
server = smtplib.SMTP('smtp.example.com')
server.sendmail(sender, receivers, msg.as_string())
server.quit()
cpu_usage = psutil.cpu_percent(interval=1)
mem_usage = psutil.virtual_memory().percent
if cpu_usage > 80 or mem_usage > 80:
send_alert("系统资源告警", f"CPU使用率: {cpu_usage}%, 内存使用率: {mem_usage}%")
fabric库实现远程服务器的代码部署(如拉取Git代码、安装依赖、重启服务)。from fabric import Connection
def deploy_app():
conn = Connection(host='user@remote-server', connect_kwargs={'key_filename': '/path/to/key'})
conn.run('git pull origin main')
conn.run('pip install -r requirements.txt')
conn.run('systemctl restart myapp')
print("应用部署完成")
deploy_app()
Python脚本需安装对应库(pip install psutil fabric),适合需要模块化、可复用的自动化任务。
对于大规模CentOS虚拟机场景,专业工具可实现配置标准化、批量操作、可视化监控:
# webserver.yml Playbook示例
- hosts: webservers # inventory中的主机组
become: yes # 以root权限执行
tasks:
- name: 安装Apache
yum:
name: httpd
state: present
- name: 启动Apache服务
service:
name: httpd
state: started
enabled: yes # 开机自启
执行命令:ansible-playbook webserver.yml,可批量管理多台CentOS虚拟机。http://<服务器IP>:9090即可使用。# main.tf 示例:创建CentOS虚拟机
resource "libvirt_domain" "centos_vm" {
name = "centos79-node01"
memory = 2048
vcpu = 2
disk {
volume_id = libvirt_volume.centos_image.id
}
network_interface {
network_name = "default"
}
cloudinit = libvirt_cloudinit_disk.commoninit.id
}
resource "libvirt_volume" "centos_image" {
name = "centos79.qcow2"
pool = "default"
source = "http://mirror.centos.org/centos/7/images/CentOS-Stream-GenericCloud-7.qcow2"
format = "qcow2"
}
执行terraform init初始化,terraform apply创建资源,实现基础设施的自动化部署与管理。sudo限制脚本执行权限,避免直接使用root用户运行脚本;对于敏感信息(如密码、API密钥),使用vault(如HashiCorp Vault)加密存储。./script.sh >> /var/log/script.log 2>&1),便于排查问题;对于关键任务(如虚拟机创建),记录操作时间、执行人、执行结果。通过以上工具与实践,可实现CentOS虚拟机从部署→配置→监控→维护的全生命周期自动化,降低人工干预风险,提升运维效率。