码迷,mamicode.com
首页 > 系统相关 > 详细

shell 脚本创建虚拟机 并配置网卡ip地址(两个脚本)

时间:2018-03-27 21:59:34      阅读:912      评论:0      收藏:0      [点我收藏+]

标签:kvm

#######################脚本1:创建虚拟机kvm#########################
#!/bin/bash
qcow2_dir=/var/lib/libvirt/images
read -p "请输入虚拟机号码:" num #主机号
if [ $num -lt 9 ];then
num=0$num ##主机号
fi
if [ -z "$num" ];then
echo "错误输出"
exit 1
fi
kvm_name=host$num #主机名字
echo "正在创建镜像........"
qemu-img create -f qcow2 -b ${qcow2_dir}/rhel7.4.qcow2 ${qcow2_dir}/${kvm_name}.qcow2 &> /dev/null ###镜像文件
echo -e "\e[32;1m[ok]\e[0m"
cat /etc/libvirt/qemu/rhel7.4.xml > /etc/libvirt/qemu/${kvm_name}.xml ##描述文件
sed -i "/<name>rhel7.4/s/rhel7.4/${kvm_name}/" /etc/libvirt/qemu/${kvm_name}.xml
sed -i "/<uuid>/d" /etc/libvirt/qemu/${kvm_name}.xml
sed -i "/<source/s/rhel7.4.qcow2/${kvm_name}.qcow2/" /etc/libvirt/qemu/${kvm_name}.xml
sed -i "/<mac address=/d" /etc/libvirt/qemu/${kvm_name}.xml #删除mac地址,开机动自动生成
virsh define /etc/libvirt/qemu/${kvm_name}.xml &> /dev/null
echo "正在创建虚拟机......."
echo -e "\e[32;1m[ok]\e[0m"
####################脚本2:eth0网卡配ip地址#####################
#!/bin/bash
clear
mountpoint="/media/virimage"
#判断不存在挂载目录
[ ! -d $mountpoint ] && mkdir $mountpoint
#如果有设备挂载到该挂载点,则先umount卸载
if mount |grep -q "$mountpoint" ;then
umount $mountpoint
fi
virsh list --all
read -p "输入虚拟机名称: " name
echo "请稍后..."
#将虚拟机的磁盘文件挂载到/media/virtimage目录
guestmount -d $name -i $mountpoint
echo "---------------------------------------"
read -p "请输入要配置的ip地址: " ip
read -p "请输入要配置的子网掩码位数: " num
#静态地址
sed -i "s;(BOOTPROTO=).;\1none;" ${mountpoint}/etc/sysconfig/network-scripts/ifcfg-eth0
#开机自起
sed -i "s;(ONBOOT=).
;\1yes;" ${mountpoint}/etc/sysconfig/network-scripts/ifcfg-eth0
#如果ip地址不存在,就添加ip地址
grep -q "IPADDR" ${mountpoint}/etc/sysconfig/network-scripts/ifcfg-eth0 || echo "IPADDR=$ip" >> ${mountpoint}/etc/sysconfig/network-scripts/ifcfg-eth0
#如果ip地址存在
sed -i "s;(IPADDR=).;\1$ip;" ${mountpoint}/etc/sysconfig/network-scripts/ifcfg-eth0
#如果子网掩码不存在,就添加子网掩码
grep -q "PREFIX" ${mountpoint}/etc/sysconfig/network-scripts/ifcfg-eth0 || echo "PREFIX=$num" >> ${mountpoint}/etc/sysconfig/network-scripts/ifcfg-eth0
#如果子网掩码存在
sed -i "s;(PREFIX=).
;\1$num;" ${mountpoint}/etc/sysconfig/network-scripts/ifcfg-eth0
echo "ifup eth0" >> ${mountpoint}/etc/rc.d/rc.local
chmod +x ${mountpoint}/etc/rc.d/rc.local
umount ${mountpoint}
sleep 0.5
virsh start $name

shell 脚本创建虚拟机 并配置网卡ip地址(两个脚本)

标签:kvm

原文地址:http://blog.51cto.com/13587169/2091787

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!