KVM管理脚本

#!/bin/bash

init() {
echo "配置yum源,所用的源为中国科技大学镜像站。"
sed -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://mirror.centos.org/centos|baseurl=https://mirrors.ustc.edu.cn/centos|g' -i.bak  /etc/yum.repos.d/CentOS-Base.repo
yum makecache &>/dev/null
echo "关闭selinux。"
setenforce 0 &>/dev/null
sed -ri '/^SELINUX=/c SELINUX=disabled' /etc/selinux/config
echo "禁用防火墙。"
systemctl stop firewalld && systemctl disable firewalld &>/dev/null
echo "安装基础软件包,如vim,wget等。"
yum -y install epel-release wget bash-completion vim-enhanced net-tools lsof lrzsz-0.12.20-36.el7.x86_64 &>/dev/null
rpm -qa wget bash-completion vim-enhanced net-tools lsof lrzsz-0.12.20-36.el7.x86_64 &>/dev/null ||echo "某些软件包安装失败。"
echo "/usr/sbin/dhclient" >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local

###以下为KVM初始化脚本
yum -y install iptables-services &>/dev/null
rpm -qa iptables.services &> /dev/null || echo "iptables安装失败。"
systemctl start iptables.service &>/dev/null
systemctl enable iptables.service &>/dev/null
echo "iptables设置转发功能。"
echo "net.ipv4.ip_forward = 1" >> /etc/sysctl.conf
iptables -t nat -A POSTROUTING -o ens33 -s 192.168.122.0/24 -j MASQUERADE
iptables-save > /etc/sysconfig/iptables
echo "安装kvm及其组件中。"
yum -y install qemu-kvm libvirt libvirt-python libguestfs-tools virt-install virt-manager &>/dev/null
systemctl enable libvirtd && systemctl start libvirtd &>/dev/null || echo "某些软件包安装失败,请检查网络,或者查看日志。"
echo "安装完成。可以使用'lsmod | grep kvm' 命令查看kvm是否运行"
}

install() {
pas=`echo "1"|openssl passwd -1 -stdin`
####配置文件,默认密码为1
cat > /home/kvm/ks.cfg <<-eof
#platform=x86, AMD64, 或 Intel EM64T
#version=DEVEL
# Install OS instead of upgrade
install
# Keyboard layouts
keyboard 'us'
# Root password
rootpw --iscrypted $pas
# 系统语言
lang zh_CN.UTF-8
#lang en_US

# System authorization information
auth  --useshadow  --passalgo=sha512
# Use CDROM installation media
#cdrom

# Use text mode install
# 使用字符界面安装操作系统
text

# Do not configure the X Window System
# 不配置图形界面系统
skipx

# SELinux configuration
selinux --disabled

# Firewall configuration
firewall --disabled

# 设置动态获取 IP
network  --bootproto=dhcp --device=eth0 --onboot=on
network  --hostname=HOSNAME

# 设置静态 IP
# network  --bootproto=static --device=eth0 --gateway=192.168.122.1 --ip=192.168.122.100 --nameserver=192.168.122.1 --netmask=255.255.255.0 --activate

# 系统安装完成后 重启系统
#halt
reboot

# System timezone 系统时区
timezone Asia/Shanghai

# System services  系统启动时候自动启动的服务
services --enable="chronyd"

# System bootloader configuration
#系统启动引导方式 vda 是kvm 虚拟机时候的第块磁盘名称
bootloader --location=mbr --boot-drive=vda

# 清除主引导记录
zerombr

# 删除原来的分区和磁盘标签
clearpart --all --initlabel

# 磁盘分区信息,这里采用的是 lvm 自动分区
autopart --type=lvm

# 下面是自定义分区
#part /boot --fstype="xfs" --ondisk=vda --size=200
#part / --fstype="xfs" --ondisk=vda --size=10040
#part /var --fstype="xfs" --ondisk=vda --size=2048
#part /home --fstype="xfs" --ondisk=vda --size=2048

# 安装软件
%packages
@^minimal
@core
chrony
%end

# 禁用 kdump
%addon com_redhat_kdump --disable --reserve-mb='auto'

%end

# 安装系统完成后执行的命令脚本
%post --interpreter=/bin/bash
sed -e 's|^mirrorlist=|#mirrorlist=|g' -e 's|^#baseurl=http://mirror.centos.org/centos|baseurl=https://mirrors.ustc.edu.cn/centos|g' -i.bak  /etc/yum.repos.d/CentOS-Base.repo
yum makecache
sed -ri '/^SELINUX=/c SELINUX=disabled' /etc/selinux/config
systemctl stop firewalld && systemctl disable firewalld
yum -y install wget bash-completion vim-enhanced net-tools lsof lrzsz-0.12.20-36.el7.x86_64
echo "/usr/sbin/dhclient" >> /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local
%end

# 用户密码策略
%anaconda
pwpolicy root --minlen=6 --minquality=1 --notstrict --nochanges --notempty
pwpolicy user --minlen=6 --minquality=1 --notstrict --nochanges --emptyok
pwpolicy luks --minlen=6 --minquality=1 --notstrict --nochanges --notempty
%end
eof

set -ue
set -o pipefail

# 创建相关目录
ls /home/kvm/{ks,virtualhost,virtual-img} 1>/dev/null 2>&1 || mkdir -p /home/kvm/{ks,virtualhost,virtual-img}
#mv /root/CentOS-7-x86_64-Minimal.iso /home/kvm/
# 此程序的变量
KVM_HOME=/home/kvm
KVM_ISO=$KVM_HOME/CentOS-7-x86_64-Minimal-1708.iso
KVM_KS_FILE=$KVM_HOME/ks.cfg
KVM_IMG_DIR=${KVM_HOME}/virtual-img

OS_TYPE="linux"
DEF_OS_VARIANT="rhel7"
DEF_VM_NAME="centos-$(date +%F-%T)"

# 设置默认内存大小 512 M,这个单位是固定的 M,不支持其他单位
DEF_MEM_SIZE=512
DEF_VCPUS=1
DEF_DISK_SIZE=10G

#  交互式安装
echo  "输入将要创建的KVM虚拟机名称,不是主机名哦"
read -p "默认值${DEF_VM_NAME}>>:" VM_NAME


echo  "输入将要创建的服务器主机名"
read -p "默认 localhost>>:"  HOST_NAME

read -p "输入虚拟机 CPU 核心数默认 1 示例:2>>:" VCPUS

echo "输入虚拟机内存大小,默认512M,不支持其他单位"
read -p "只需要添数字即可>>:" MEM_SIZE

echo "输入虚拟机使用的磁盘容量"
read -p "默认 10G,[示例写法:15G]>>:"  DISK_SIZE


# 变量替换, 假如没有输入值, 就使用默认值
VM_NAME=${VM_NAME:-$DEF_VM_NAME}
HOST_NAME=${HOST_NAME:-localhost.localdomain}

VCPUS=${VCPUS:-$DEF_VCPUS}
MEM_SIZE=${MEM_SIZE:-$DEF_MEM_SIZE}
DISK_SIZE=${DISK_SIZE:-$DEF_DISK_SIZE}
OS_VARIANT=${OS_VARIANT:-$DEF_OS_VARIANT}

new_disk=${KVM_IMG_DIR}/${VM_NAME}.qcow2


if [[ ! "${DISK_SIZE}" =~ G$ ]] || [[ ! "${DISK_SIZE::-1}" =~ ^[0-9]+$ ]]
then
    echo "格式不正确,正确示例:20G"
    exit
fi


if [ ! -f "${new_disk}" ];then
    qemu-img create -f qcow2 ${new_disk} ${DISK_SIZE}
fi


# 开始创建

virt-install -v \
     --arch x86_64 --virt-type kvm \
     --name ${VM_NAME} \
     --memory ${MEM_SIZE} \
     --vcpus ${VCPUS} \
     --os-type ${OS_TYPE} \
     --location ${KVM_ISO} \
     --network default \
     --graphics none \
     --os-variant     ${OS_VARIANT} \
     --initrd-inject  "${KVM_KS_FILE}" \
     --extra-args     "ks=file:/ks.cfg  \
                       console=tty0 console=ttyS0,115200n8 \
                       hostname=${HOST_NAME}" \
     --disk ${new_disk},cache=writeback,io=threads,bus=virtio

# 桥接模式,前提是你已经建立好了网桥
#     --network bridge=br0  \
# end
}

add_disk() {
read -p "请输入要添加硬盘的设备:" devname
read -p "请输入添加多大的硬盘:" n

cd /home/kvm/virtual-img

for i in {a..z}
do
    virsh domblklist $devname |grep -E  "^vd$i" &>/dev/null
    if [ $? -ne 0 ];then
        break
    fi
done
disk=vd$i
if [ ! -f "/home/kvm/virtual-img/$devname-$disk.qcow2" ];then
    qemu-img create -f qcow2 /home/kvm/virtual-img/$devname-$disk.qcow2 $n
fi
cat > $devname-$disk.xml <<-eof
<disk type='file' device='disk'>
  <driver name='qemu' type='qcow2' cache='writeback' io='threads'/>
  <source file='/home/kvm/virtual-img/$devname-$disk.qcow2'/>
  <target dev='$disk' bus='virtio'/>
</disk>
eof
virsh attach-device $devname $devname-$disk.xml --persistent
ls /home/kvm/virtual-img/$devname-$disk.xml &>/dev/null && rm -rf ./$devname-$disk.xml
}

add_network() {
defmode=default
read -p "请输入要添加网卡的设备:" netname
read -p "请输入要添加的网卡模式,默认为NAT模式,桥接为BR:" mode
mode=${mode:-$defmode}
if [ "$mode" == "NAT" ];then
    newmac=$(openssl rand -hex 3 | sed -r 's/..\B/&:/g')
    cat >network.xml <<-eof
<interface type='network'>
  <mac address='52:54:00:$newmac'/>
  <source network='$mode'/>
  <model type='virtio'/>
</interface>
eof
    virsh attach-device $netname network.xml --persistent
    ls ./network.xml &>/dev/null && rm -rf ./network.xml
elif [ "$mode" == "BR" ];then
    read -p "请输入桥接网卡名称:" neteth
    newmac=$(openssl rand -hex 3 | sed -r 's/..\B/&:/g')
     cat >network.xml <<-eof
<interface type='bridge'>
      <mac address='52:54:00:$newmac'/>
      <source bridge='$neteth'/>
      <model type='rtl8139'/>
    </interface>
eof
    virsh attach-device $netname network.xml --persistent
    ls ./network.xml &>/dev/null && rm -rf ./network.xml
fi
}
del_disk() {
read -p "请输入虚拟机名称:" name
read -p "请输入要删除的disk名称:" deldisk
path=$(virsh domblklist centos7_0 |grep $deldisk|awk '{print $2}')
virsh detach-disk $name $deldisk --persistent
ls $path &>/dev/null && rm -rf $path
}
del_network() {
read -p "请输入虚拟机名称:" name
read -p "请输入要删除的网卡名称:" delint
type=$(virsh domiflist $name | grep "$delint" |awk '{print$2}')
mac=$(virsh domiflist $name | grep "$delint" |awk '{print$5}')
virsh detach-interface $name  --persistent --mac $mac --type $type --config --live
}

copy_install() {
ls /home/kvm/{ks,virtualhost,virtual-img} 1>/dev/null 2>&1 || mkdir -p /home/kvm/{ks,virtualhost,virtual-img}
cd /home/kvm/virtual-img
defvm_mem=524288
defvm_name=$(date +%F-%T)
read -p "请输入虚拟机名:" vm_name
read -p "请输入虚拟机内存,如524288:" vm_mem
read -p "请输入要克隆的虚拟机磁盘,使用绝对路径如/home/kvm/virtual-img/centos7_0.qcow2:" vm_disk_path_file
vm_mem=${vm_mem:-$defvm_mem}
vm_name=${vm_name:-$defvm_name}
 vm_uuid=$(uuidgen)
 vm_disk_path=$(echo ${vm_disk_path_file%/*})
 vm_mac=$(openssl rand -hex 3 | sed -r 's/..\B/&:/g')
cat >/etc/libvirt/qemu/$vm_name.xml <<-eof
<!--
     WARNING: THIS IS AN AUTO-GENERATED FILE. CHANGES TO IT ARE LIKELY TO BE
OVERWRITTEN AND LOST. Changes to this xml configuration should be made using:
  virsh edit centos7
or other application using the libvirt API.
-->

<domain type='kvm'>
  <name>$vm_name</name>  <!--这里修改了-->
  <uuid>$vm_uuid</uuid>  <!--这里修改了-->
  <memory unit='KiB'>$vm_mem</memory>  <!--这里修改了-->
  <currentMemory unit='KiB'>$vm_mem</currentMemory>  <!--这里修改了-->
  <vcpu placement='static'>1</vcpu>
  <os>
    <type arch='x86_64' machine='pc-i440fx-rhel7.0.0'>hvm</type>
    <boot dev='hd'/>
  </os>
  <features>
    <acpi/>
    <apic/>
  </features>
  <cpu mode='custom' match='exact' check='partial'>
    <model fallback='allow'>Broadwell-noTSX-IBRS</model>
    <feature policy='require' name='spec-ctrl'/>
    <feature policy='require' name='ssbd'/>
  </cpu>
  <clock offset='utc'>
    <timer name='rtc' tickpolicy='catchup'/>
    <timer name='pit' tickpolicy='delay'/>
    <timer name='hpet' present='no'/>
  </clock>
  <on_poweroff>destroy</on_poweroff>
  <on_reboot>restart</on_reboot>
  <on_crash>destroy</on_crash>
  <pm>
    <suspend-to-mem enabled='no'/>
    <suspend-to-disk enabled='no'/>
  </pm>
  <devices>
    <emulator>/usr/libexec/qemu-kvm</emulator>
    <disk type='file' device='disk'>
      <driver name='qemu' type='qcow2'/>
      <source file='$vm_disk_path/$vm_name.qcow2'/>  <!--这里修改了-->
      <target dev='vda' bus='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x06' function='0x0'/>
    </disk>
    <disk type='file' device='cdrom'>
      <driver name='qemu' type='raw'/>
      <target dev='hda' bus='ide'/>
      <readonly/>
      <address type='drive' controller='0' bus='0' target='0' unit='0'/>
    </disk>
    <controller type='usb' index='0' model='ich9-ehci1'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x7'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci1'>
      <master startport='0'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0' multifunction='on'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci2'>
      <master startport='2'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x1'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci3'>
      <master startport='4'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x2'/>
    </controller>
    <controller type='pci' index='0' model='pci-root'/>
    <controller type='ide' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>
    </controller>
    <controller type='virtio-serial' index='0'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
    </controller>
    <interface type='network'>
      <mac address='52:54:00:$vm_mac'/>  <!--这里修改了-->
      <source network='default'/>
      <model type='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>
    </interface>
    <serial type='pty'>
      <target type='isa-serial' port='0'>
        <model name='isa-serial'/>
      </target>
    </serial>
    <console type='pty'>
      <target type='serial' port='0'/>
    </console>
    <channel type='unix'>
      <target type='virtio' name='org.qemu.guest_agent.0'/>
      <address type='virtio-serial' controller='0' bus='0' port='1'/>
    </channel>
    <channel type='spicevmc'>
      <target type='virtio' name='com.redhat.spice.0'/>
      <address type='virtio-serial' controller='0' bus='0' port='2'/>
    </channel>
    <input type='tablet' bus='usb'>
      <address type='usb' bus='0' port='1'/>
    </input>
    <input type='mouse' bus='ps2'/>
    <input type='keyboard' bus='ps2'/>
    <graphics type='spice' autoport='yes'>
      <listen type='address'/>
      <image compression='off'/>
    </graphics>
    <video>
      <model type='qxl' ram='65536' vram='65536' vgamem='16384' heads='1' primary='yes'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>
    </video>
    <memballoon model='virtio'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x07' function='0x0'/>
    </memballoon>
    <rng model='virtio'>
      <backend model='random'>/dev/urandom</backend>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x08' function='0x0'/>
    </rng>
  </devices>
</domain>
eof
echo "复制虚拟机中。 "
cp $vm_disk_path_file $vm_disk_path/$vm_name.qcow2
virsh define /etc/libvirt/qemu/$vm_name.xml
echo "完成"
}

create_snapshot() {
read -p "输入要操作的虚拟机:" name
cat <<-eof
#######################################
1,创建虚拟机快照
2,通过快照还原虚拟机
3,删除虚拟机快照
#######################################
eof
read -p "请输入您的选择:" cho

case $cho in
1)
read -p "请输入需要创建的快照名称:" sname
virsh snapshot-create-as $name $sname
;;
2)
virsh snapshot-list  $name
read -p "需要还原到的快照:" sname
virsh snapshot-revert $name --snapshotname $sname
;;
3)
virsh snapshot-list  $name
read -p "需要删除的快照:" sname
virsh snapshot-delete $name --snapshotname $sname
;;
esac
}
####如宿主机使用静态IP请自行修改
create_br() {
read -p "请输入桥接到的网卡:" neteth
read -p "请输入需要创建的桥接网卡:" brdg
cat > /etc/sysconfig/network-scripts/ifcfg-$brdg <<-eof
TYPE=Bridge
NAME=br0
DEVICE=br0
ONBOOT="yes"
BOOTPROTO=dhcp
#IPADDR=192.168.98.128
#GATEWAY=192.168.98.2
#NETMASK=255.255.255.0
#DNS1=114.114.114.114
#DNS2=8.8.8.8
eof
mv /etc/sysconfig/network-scripts/ifcfg-$neteth  /etc/sysconfig/network-scripts/ifcfg-$neteth.bak
cat > /etc/sysconfig/network-scripts/ifcfg-$neteth <<-eof
NAME=$neteth
DEVICE=$neteth
ONBOOT=yes
BRIDGE=br0
eof
systemctl restart libvirtd
systemctl restart network
}
delete_br() {
read -p "请输入需要删除的被桥接网卡,请勿输入特殊字符,如*号:" neteth
read -p "请输入需要删除的桥接网卡:" brdg
rm -rf /etc/sysconfig/network-scripts/ifcfg-$neteth
rm -rf /etc/sysconfig/network-scripts/ifcfg-$brdg
mv /etc/sysconfig/network-scripts/ifcfg-$neteth.bak  /etc/sysconfig/network-scripts/ifcfg-$neteth
systemctl restart libvirtd
systemctl restart network
}


while :
do

cat <<-eof
****************************************************************
1,安装kvm,并配置环境
2,安装centos7虚拟机,请将镜像文件放到/home/kvm下
3,对设备添加硬盘
4,对设备添加网卡
5,对设备删除硬盘
6,对设备删除网卡
7,克隆虚拟机
8,快照操作
9,创建桥接网卡
10,删除桥接网卡

按其他键退出脚本
****************************************************************
eof

read -p "请输入你的选择:" choice
case $choice in
1)
init
;;
2)
install
;;
3)
add_disk
;;
4)
add_network
;;
5)
del_disk
;;
6)
del_network
;;
7)
copy_install
;;
8)
create_snapshot
;;
9)
create_br
;;
10)
delete_br
;;
*)
exit
;;
esac
done
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值