linux一键克隆,使用shell一键克隆虚拟机

说明:此脚本是通过快照技术快速的一键克隆虚拟机,脚本只限于CentOS和Redhat。

输入数字后会创建一个以标号标识的虚拟机。

代码如下:

#!/bin/bash

# exit code:

# 65 -> user input nothing

# 66 -> user input is not a number

# 67 -> user input out of range

# 68 -> vm disk image exists

IMG_DIR=/var/lib/libvirt/images

BASEVM=rh7_template

###BASEVM为后端的img文件名,此文件名根据自己需求更改!!!

ROOM=sed -n "1p" /etc/hostname | sed -r 's/(room)([0-9]{1,})(.*)/\2/'

if [ $ROOM -le 9 ];then

ROOM=0$ROOM

fi

IP=sed -n "1p" /etc/hostname | sed -r 's/(.*)([0-9]+)(.*)/\2/'

read -p "Enter VM number: " VMNUM

if [ $VMNUM -le 9 ];then

VMNUM=0$VMNUM

fi

if [ -z "${VMNUM}" ]; then

echo "You must input a number."

exit 65

elif [ $(echo ${VMNUM}*1 | bc) = 0 ]; then

echo "You must input a number."

exit 66

elif [ ${VMNUM} -lt 1 -o ${VMNUM} -gt 99 ]; then

echo "Input out of range"

exit 67

fi

NEWVM=rh7_node${VMNUM}

if [ -e $IMG_DIR/${NEWVM}.img ]; then

echo "File exists."

exit 68

fi

echo -en "Creating Virtual Machine disk image......\t"

qemu-img create -f qcow2 -b $IMG_DIR/.${BASEVM}.img $IMG_DIR/${NEWVM}.img &> /dev/null

echo -e "\e[32;1m[OK]\e[0m"

#virsh dumpxml ${BASEVM} > /tmp/myvm.xml

cat /var/lib/libvirt/images/.rhel7.xml > /tmp/myvm.xml

###rhel7.xml此文件需要存在!!!

sed -i "/${BASEVM}/s/${BASEVM}/${NEWVM}/" /tmp/myvm.xml

sed -i "/uuid/s/.*/$(uuidgen)/" /tmp/myvm.xml

sed -i "/${BASEVM}.img/s/${BASEVM}/${NEWVM}/" /tmp/myvm.xml

sed -i "/mac /s/a1/${ROOM}/" /tmp/myvm.xml

sed -i "/mac /s/a2/${IP}/" /tmp/myvm.xml

sed -i "/mac /s/a3/${VMNUM}/" /tmp/myvm.xml

sed -i "/mac /s/b1/${ROOM}/" /tmp/myvm.xml

sed -i "/mac /s/b2/${IP}/" /tmp/myvm.xml

sed -i "/mac /s/b3/${VMNUM}/" /tmp/myvm.xml

sed -i "/mac /s/c1/${ROOM}/" /tmp/myvm.xml

sed -i "/mac /s/c2/${IP}/" /tmp/myvm.xml

sed -i "/mac /s/c3/${VMNUM}/" /tmp/myvm.xml

sed -i "/mac /s/d1/${ROOM}/" /tmp/myvm.xml

sed -i "/mac /s/d2/${IP}/" /tmp/myvm.xml

sed -i "/mac /s/d3/${VMNUM}/" /tmp/myvm.xml

echo -en "Defining new virtual machine......\t\t"

virsh define /tmp/myvm.xml &> /dev/null

echo -e "\e[23;1m[OK]\e[0m"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值