对于rhel9
[root@rh9-node1 ~]# vim /usr/bin/vmset.sh
#!/bin/bash
# 检查网络接口是否存在
ifconfig "$1" &> /dev/null || {
echo "net device $1 is not exist"
exit
}
# 检查目标IP是否可达
ping -c1 -w1 "$2" &> /dev/null && {
echo "$2 is exist"
exit
}
# 删除旧的连接配置
grep "$1" -r /etc/NetworkManager/system-connections/ | awk -F: '{system("rm -fr " $1)}'
# 创建新的连接配置文件
cat > /etc/NetworkManager/system-connections/"$1".nmconnection <<EOF
[connection]
id=$1
type=ethernet
interface-name=$1
[ipv4]
method=manual
address1=$2/24,172.25.254.2
dns=8.8.8.8
EOF
# 设置权限并重新加载连接
chmod 600 /etc/NetworkManager/system-connections/"$1".nmconnection
nmcli connection reload
nmcli connection up "$1"
# 设置主机名
hostnamectl hostname "$3"
grep -q -e "$2\t$3" /etc/hosts || {
echo -e "$2\t$3" >> /etc/hosts
}
[root@rh9-node1 ~]# vmset.sh eth1 172.25.254.20 node1.timinglee.org
-bash: /usr/bin/vmset.sh: 权限不够
[root@rh9-node1 ~]# chmod +x /usr/bin/vmset.sh
[root@rh9-node1 ~]# vmset.sh eth1 172.25.254.20 node1.timinglee.org
连接已成功激活(D-Bus 活动路径:/org/freedesktop/NetworkManager/ActiveConnection/6)
原来的eth1的IP
通过脚本修改后的IP
对于rhel7
[root@rh7-node1 ~]# vim /usr/bin/vmset.sh
#!/bin/bash
# 检查网络接口是否存在
if ! ifconfig "$1" &>/dev/null && ! ip link show "$1" &>/dev/null; then
echo "网络设备 $1 不存在,可用设备: $(ls /sys/class/net/ | tr '\n' ' ')"
exit 1
fi
# 检查目标IP是否可达
if ping -c1 -w1 "$2" &>/dev/null; then
echo "IP地址 $2 已被占用"
exit 1
fi
# 删除旧的连接配置
find /etc/sysconfig/network-scripts/ -name "ifcfg-*" -exec grep -l "$1" {} + | xargs rm -f
# 创建新的连接配置文件(RHEL7格式)
cat > /etc/sysconfig/network-scripts/ifcfg-"$1" <<EOF
DEVICE=$1
NAME=$1
TYPE=Ethernet
BOOTPROTO=none
IPADDR=$2
NETMASK=255.255.255.0
GATEWAY=172.25.254.2
DNS1=8.8.8.8
ONBOOT=yes
EOF
# 重启网络服务(RHEL7方式)
systemctl restart network
# 设置主机名
hostnamectl set-hostname "$3"
# 更新/etc/hosts文件
if ! grep -q "$2.*$3" /etc/hosts; then
echo "$2 $3" >> /etc/hosts
fi