kvm虚拟机自动化安装,shell脚本。

[root@localhost kvm]# tree /kvm
/kvm
├── disk             #虚拟磁盘存放位置
│   ├── wc1.qcow2
│   ├── wc2.qcow2
│   └── wc.qcow2
├── kvm-manager.sh   #执行脚本
├── lib
│   ├── 1
│   ├── function.func   #调用函数
│   └── install-new.sh
├── module              #函数所用模板
│   ├── centos7-mod.xml
│   ├── disk-mod.xml
│   ├── ks.cfg
│   └── network-mod.xml
└── tmp                #存放xml文件
    ├── centos7_wc1.xml
    ├── centos7_wc2.xml
    ├── centos7_.xml
    ├── disk_centos20201210T210142.xml
    ├── network_centos20201210T210142.xml
    └── network.xml

4 directories, 18 files

[root@localhost kvm]# cat kvm-manager.sh

source ./lib/function.func

show_meu(){
cat <<EOF
1 查看当前所有的虚拟机   2 全新自动化安装虚拟机

3 利用模板快速创建虚拟机  4 给指定的虚拟机添加磁盘

5 给指定的虚拟机添加网卡  * 输入其他退出

EOF

}

while true
do
  show_meu
  read -p "开始你的选择>>:"  choice
  case $choice in
   1)
     show_all
     ;;
   2)
     gen_new
     ;;
   3)
     fast_new
     ;;
   4)
     add_disk
     ;;
   5)
     add_net
     ;;
   *)
     echo "退出!!!"
     break
    ;;
  esac
done
[root@localhost lib]# cat function.func
show_all (){
  virsh  list --all
}



gen_new(){
  source ./lib/install-new.sh
}



fast_new(){

  echo "利用模板创建一个新的虚拟机"

  read -p "name:>>" vm_name

  vm_uuid=$(uuidgen)
  vm_mac=$(openssl rand -hex 3 | sed -r 's/..\B/&:/g')
  read -p "磁盘路径(例如:/kvm/disk/xxx.qcow2)>>" vm_disk_path

  read -p "磁盘名字:>>" vm_disk_name

  source ./module/centos7-mod.xml > ./tmp/centos7_${vm_name}.xml
  cp /home/kvm/virtual-img/centos20201210T210142.qcow2 ./disk/${vm_name}.qcow2   #注意我这里是有已经创好的虚拟机文件
  virsh define ./tmp/centos7_${vm_name}.xml
  virsh start ${vm_name}
  virsh domifaddr ${vm_name}

}

add_disk(){
  echo "给指定的虚拟机添加硬盘"
  look=`virsh list --all | awk 'NR !=1 && NR !=2 {printf "%s,%s",$2," "}'`
  echo "现有的虚拟机有${look}"

  read -p "请输入创建磁盘的容量(例如:2)(G)>>:" disk_size

  read -p "请输入虚拟机配置文件的路径(例如:/kvm/disk/xxx.qcow2)>>:" config_file_path
  read -p "输入添加磁盘的虚拟机名字>>:" vm_name
  vir_shell=$(virsh domblklist ${vm_name} | grep ^vd | awk '{print$1}' | tail -1) # 获取最后一行
  letter=${vir_shell:2:1}  # 截取最后一个字母
  num=$(printf "%d" "'${letter}")
  if [[ "$num" == 122 ]];then
    echo "输入错误。。不能继续创建。。。"
    exit
  fi
  next_num=$(($num + 1))
  next_letter=$(printf \\x`printf %x ${next_num}`)
  new_disk_name="vd${next_letter}"
# echo $new_disk_name
  qemu-img create -f qcow2 ${config_file_path} ${disk_size}G
  source ./module/disk-mod.xml > ./tmp/disk_${vm_name}.xml
  virsh attach-device ${vm_name} ./tmp/disk_${vm_name}.xml --persistent
  virsh domblklist ${vm_name}



}

add_net(){
#给指定的虚拟机添加网卡
     look=`virsh list --all | awk 'NR !=1 && NR !=2 {printf "%s,%s",$2," "}'`
    echo "现有的虚拟机有${look}"
    read -p "输入需要添加网卡的虚拟机名称>>:" vm_name

    mac=$(openssl rand -hex 3 | sed -r 's/..\B/&:/g')
    echo "已经给虚拟机[${vm_name}] 创建了 MAC:${mac}"
    source ./module/network-mod.xml > ./tmp/network_${vm_name}.xml
    echo "已经创建了 XML 配置文件"
    virsh attach-device ${vm_name} ./tmp/network_${vm_name}.xml --persistent
    echo "已经添加了网卡"
    virsh domiflist ${vm_name}
}
[root@localhost lib]# cat install-new.sh
#!/usr/bin/env bash
set -ue
set -o pipefail

# 设置 kvm 虚拟机家目录
KVM_HOME=/kvm


# 创建相关目录
ls ${KVM_HOME}/virtual-img 1>/dev/null 2>&1 || mkdir -p ${KVM_HOME}/virtual-img


# 此程序的变量
KVM_ISO=${KVM_HOME}/CentOS-7-x86_64-Minimal.iso
KVM_KS_FILE=./module/ks.cfg
KVM_IMG_DIR=${KVM_HOME}/virtual-img

OS_TYPE="linux"
DEF_OS_VARIANT="rhel7"
DEF_VM_NAME="centos$(date +%Y%m%dT%H%M%S)"

# 设置默认内存大小 1024 M,这个单位是固定的 M,不支持其他单位
DEF_MEM_SIZE=1024
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 "输入虚拟机内存大小,默认1024M,不支持其他单位"
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
[root@localhost module]# cat centos7-mod.xml  #注意自己的机器在cpu等方面参数会有不同,注意。
echo "<!--
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-1
or other application using the libvirt API.
-->

<domain type='kvm'>
  <name>${vm_name}</name>
  <uuid>${vm_uuid}</uuid>
  <memory unit='KiB'>1048576</memory>
  <currentMemory unit='KiB'>1048576</currentMemory>
  <vcpu placement='static'>2</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='full'>
    <model fallback='forbid'>SandyBridge</model>
    <feature policy='require' name='hypervisor'/>
    <feature policy='require' name='xsaveopt'/>
  </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}'/>
      <target dev='${vm_disk_name}' bus='virtio'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x07' 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='0x05' function='0x7'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci1'>
      <master startport='0'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0' multifunction='on'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci2'>
      <master startport='2'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x1'/>
    </controller>
    <controller type='usb' index='0' model='ich9-uhci3'>
      <master startport='4'/>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x05' 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='0x06' 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>
    <sound model='ich6'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
    </sound>
    <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>
    <redirdev bus='usb' type='spicevmc'>
      <address type='usb' bus='0' port='2'/>
    </redirdev>
    <redirdev bus='usb' type='spicevmc'>
      <address type='usb' bus='0' port='3'/>
    </redirdev>
    <memballoon model='virtio'>
      <address type='pci' domain='0x0000' bus='0x00' slot='0x08' function='0x0'/>
    </memballoon>
  </devices>
</domain>"
[root@localhost module]# cat disk-mod.xml
echo "<disk type='file' device='disk'>
  <driver name='qemu' type='qcow2' cache='writeback' io='threads'/>
  <source file='${config_file_path}'/>
  <target dev='${new_disk_name}' bus='virtio'/>
</disk>"
[root@localhost module]# cat ks.cfg
#platform=x86, AMD64, 或 Intel EM64T
#version=DEVEL
# Install OS instead of upgrade
install
# Keyboard layouts
keyboard 'us'
# Root password
rootpw --iscrypted $1$KXeyOPUO$5JlUe3pPpi.hplHB71JdX/
# 系统语言
#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
yum install -y epel-release bash-completion vim-enhanced wget
yum group install "Development Tools" -y
%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
[root@localhost module]# cat network-mod.xml
echo "<interface type='network'>
  <mac address='52:54:00:${mac}'/>
  <source network='default'/>
  <model type='virtio'/>
</interface>"
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值