Linux批量配置静态IP可以通过多种方式进行,以下是详细的基础概念、优势、类型、应用场景以及解决方案。
静态IP(Static IP)是指手动分配给设备的固定IP地址,而不是通过DHCP(动态主机配置协议)自动获取。静态IP地址在网络中保持不变,适用于需要稳定访问的服务,如服务器、打印机等。
以下是通过Shell脚本批量配置静态IP的示例:
创建一个模板文件static_ip_template.conf
:
DEVICE={{interface}}
BOOTPROTO=none
ONBOOT=yes
IPADDR={{ip}}
NETMASK={{netmask}}
GATEWAY={{gateway}}
DNS1={{dns1}}
创建一个脚本batch_set_static_ip.sh
:
#!/bin/bash
# 定义配置信息
declare -A servers=(
["server1"]="eth0 192.168.1.10 255.255.255.0 192.168.1.1 8.8.8.8"
["server2"]="eth1 192.168.1.20 255.255.255.0 192.168.1.1 8.8.4.4"
# 添加更多服务器配置
)
# 遍历服务器列表并应用配置
for server in "${!servers[@]}"; do
IFS=' ' read -r -a config <<< "${servers[$server]}"
interface=${config[0]}
ip=${config[1]}
netmask=${config[2]}
gateway=${config[3]}
dns1=${config[4]}
# 替换模板文件中的变量并应用配置
sed -e "s/{{interface}}/$interface/g" \
-e "s/{{ip}}/$ip/g" \
-e "s/{{netmask}}/$netmask/g" \
-e "s/{{gateway}}/$gateway/g" \
-e "s/{{dns1}}/$dns1/g" static_ip_template.conf > /etc/sysconfig/network-scripts/ifcfg-$interface
# 重启网络服务以应用更改
systemctl restart network
done
echo "静态IP配置完成"
在每台需要配置的服务器上运行该脚本:
chmod +x batch_set_static_ip.sh
./batch_set_static_ip.sh
systemctl restart network
命令成功执行,可以通过查看日志确认:systemctl restart network
命令成功执行,可以通过查看日志确认:通过以上步骤,可以高效地在多台Linux服务器上批量配置静态IP地址。
领取专属 10元无门槛券
手把手带您无忧上云