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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了shell 脚本创建虚拟机 并配置网卡ip地址(两个脚本)相关的知识,希望对你有一定的参考价值。

#######################脚本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地址(两个脚本)的主要内容,如果未能解决你的问题,请参考以下文章

在两台计算机上各打开一台虚拟机,设为桥接,IP自动获取,为啥两台虚拟机的IP地址相同?如何解决?

虚拟机配置Ubuntu的网卡DHCP动态获取ip

centos 7虚拟机怎么配置网卡eno 16

VMware中安装CentOS 6.5版本虚拟机&配置IP地址实现远程连接

虚拟机最小化安装和网卡配置

虚拟机centos7两张桥接的网卡怎么设置ip 一个是连接内网的 一个是连接外网的