#!/usr/bin/bash </dev/null if [ $? -eq 0 ]; then echo "IP地址已被使用,请更换" exit 1 fi KVM_ADDRESS=$1 shift ;; -p|--port) shift ss -tnlp | grep :$1 &>/dev/null if [ $? -eq 0 ]; then echo "端口已被使用,请更换" exit 1 fi KVM_PORT=$1 shift ;; -n|--name) shift virsh list --all | awk '{print $2}' | grep -E "^$1$" &>/dev/null if [ $? -eq 0 ]; then echo "名称已被使用,请更换" exit 1 fi VM_HOSTNAME=$1 shift ;; -c|--cpus) shift cpus=`lscpu | awk '/^CPU\(s\):/{print $2}'` vmcpus=${1:-"$KVM_CPUS"} if [ $vmcpus -ge $cpus ]; then echo "CPU数量不能大于系统的CPU数量,宿主机cpu数量为:$cpus" exit 1 fi KVM_CPUS=$vmcpus shift ;; -m|--memory) shift vmmemory=${1:-"$KVM_MEMORY"} memory=`free -m | awk '/^Mem:/{print $2}'` if [ $vmmemory -ge $memory ]; then echo "内存不能大于系统的内存,宿主机内存为:$memory" exit 1 fi KVM_MEMORY=`echo $vmmemory | grep -o -P '\d+'` shift ;; --) shift break ;; *) echo "参数错误!" exit 1 ;; esac done if [ ! -d ${MOUNT_PATH} ];then mkdir -p ${MOUNT_PATH} fi qemu-img create -f qcow2 -b ${TEMPLATE_PATH}/${TEMPLATE_IMAGE_NAME} ${VDISKS_PATH}/${VM_HOSTNAME}.qcow2 guestmount -a ${VDISKS_PATH}/${VM_HOSTNAME}.qcow2 -m /dev/centos/root ${MOUNT_PATH} /usr/bin/cp -f ${TEMPLATE_PATH}/${TEMPLATE_NETWORK_NAME} ${MOUNT_PATH}/etc/sysconfig/network-scripts/ifcfg-eth0 sed -ri "s/^IPADDR.*/IPADDR=${KVM_ADDRESS}/" ${MOUNT_PATH}/etc/sysconfig/network-scripts/ifcfg-eth0 sed -ri "s/^GATEWAY.*/GATEWAY=${KVM_ADDRESS%.*}.2/" ${MOUNT_PATH}/etc/sysconfig/network-scripts/ifcfg-eth0 sed -ri "s/.*/${VM_HOSTNAME}/" ${MOUNT_PATH}/etc/hostname cp ${TEMPLATE_PATH}/${TEMPLATE_REGISTER_NAME} ${MOUNT_PATH}/opt && \ echo "python3 /opt/${TEMPLATE_REGISTER_NAME}" >> ${MOUNT_PATH}/etc/rc.d/rc.local && \ chmod a+x ${MOUNT_PATH}/etc/rc.d/rc.local guestunmount ${MOUNT_PATH} cp ${TEMPLATE_PATH}/${TEMPLATE_CONFIG_NAME} ${CONFIG_PATH}/${VM_HOSTNAME}.xml sed -ri "s/VM_NAME/${VM_HOSTNAME}/" ${CONFIG_PATH}/${VM_HOSTNAME}.xml sed -ri "s/VM_VNC_PORT/${KVM_PORT}/" ${CONFIG_PATH}/${VM_HOSTNAME}.xml sed -ri "s#IMAGE_PATH#${VDISKS_PATH}/${VM_HOSTNAME}.qcow2#" ${CONFIG_PATH}/${VM_HOSTNAME}.xml sed -ri "s/VM_UUID/`uuidgen`/" ${CONFIG_PATH}/${VM_HOSTNAME}.xml sed -ri "s/VM_MEMORY/$[${KVM_MEMORY} * 1024 ]/" ${CONFIG_PATH}/${VM_HOSTNAME}.xml sed -ri "s/VM_CPUS/${KVM_CPUS}/" ${CONFIG_PATH}/${VM_HOSTNAME}.xml virsh define ${CONFIG_PATH}/${VM_HOSTNAME}.xml virsh start ${VM_HOSTNAME}