虚拟主机复制后的网络初始化设置

Virtual Box 复制生成新的主机虽然可以选择“重新初始化所有网卡的 MAC 地址”,但生成的新虚拟机还保留有原来的 MAC,

在 "/etc/udev/rules.d/70-persistent-net.rules" 文件里面,可看到有两个网卡信息:第一个是跟原来的虚拟主机相同,第二个是新生成的网卡:

# PCI device 0x8086:0x100e (e1000)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="08:00:27:47:1a:47", ATTR{type}=="1", KERNEL=="eth*", NAME="eth0"
# PCI device 0x8086:0x100e (e1000)
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", ATTR{address}=="08:00:27:cc:e0:5d", ATTR{type}=="1", KERNEL=="eth*", NAME="eth1"

我们要把原来的信息删去,避免和原来的主机 MAC 冲突,通过以下脚本来实现,这个脚本也实现了以交互方式设置 IP 地址,设置主机名:

cat vb_relicate_init.sh
#!/bin/bash
#
# Init for virtual box replication.
#
# modify /etc/udev/rules.d/70-persistent-net.rules,
# set new IP, MAC in ifcfg-eth0
#
# 

NET_RULES="/etc/udev/rules.d/70-persistent-net.rules"
IF_ETH0="/etc/sysconfig/network-scripts/ifcfg-eth0"
HOST_CNF="/etc/sysconfig/network"

# delete eth0 from replication 如果有两条信息,删掉第一条,第二条改名顶替第一条信息
if [ $(grep '^SUBSYSTEM' $NET_RULES | wc -l) -eq 2 ]; then
    sed -i '/eth0/d' $NET_RULES

    # set new info: NAME='eth1' -> NAME='eth0'
    sed -i 's/eth1/eth0/' $NET_RULES && echo "set eht1 -> eth0"

    echo "old info deleted"
else
    echo "need no delete"
fi



# get NEW_MAC 获取自动生成的新 MAC 地址
NEW_MAC=$(grep 'eth0' $NET_RULES | cut -d',' -f4 | cut -d'=' -f3)
if [ -z "$NEW_MAC" ]; then
    exit 3;
fi

# set HWADDR 在 ifcfg-eth0 文件中修改 MAC 地址
sed -i "s/HWADDR=.*/HWADDR=$NEW_MAC/" $IF_ETH0

# reload net drive module 卸载网卡驱动模块,然后重新加载
modprobe -r e1000; modprobe e1000

# set new IP 手动输入新 IP,然后修改 ifcfg-eth0 文件中的 IPADDR 参数为新的IP
read -p "please input a new IP: " NEW_IP
sed -i "s/IPADDR=.*/IPADDR=$NEW_IP/" $IF_ETH0

echo "new MAC, IP is set to: "
grep -E "IPADDR|HWADDR" $IF_ETH0

# set new hostname 设置主机名
read -p "please input a new hostname: " NEW_HOST
sed -i "s/HOSTNAME=.*/HOSTNAME=$NEW_HOST/" $HOST_CNF
echo "new hostname is set to :"
grep "HOSTNAME" $HOST_CNF
echo "hostname update will be in effective after restart"

# restart network 重启网络
echo "restart network"
service network restart

# restart ? 是否立即重启主机
read -p "restart now? [yes|no] " RESTART
if [ "yes" = $RESTART ]; then
    shutdown -r now
else
    echo "init work done, a restart is needed for new HOSTNAME in effective"
fi

你可能感兴趣的:(虚拟主机复制后的网络初始化设置)