Ubuntu 20.04 LTS 批量永久添加 IP 地址
Ubuntu 20.04 LTS 批量永久添加 IP 地址
2023-10-26 06:23
在 Ubuntu 20.04 LTS 中,网络管理仍然是由 `Netplan` 处理的。以下是一个脚本,用于基于 。
请确保您已经安装了 `netplan.io` 和 `networkd`(这通常是默认的)。然后,使用以下脚本来添加 IP 地址。
脚本名称:`add_ips_ubuntu2004.sh`
```bash
#!/bin/bash
# Network interface (Modify if different)
INTERFACE="ens33"
# Check if IP range start and end are provided
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <IP_START> <IP_END>"
exit 1
fi
IP_START=$1
IP_END=$2
# Function to convert IP to number
ip_to_int()
{
local a b c d
IFS=. read -r a b c d <<< "$1"
echo "$((a * 256 ** 3 + b * 256 ** 2 + c * 256 + d))"
}
# Function to convert number to IP
int_to_ip()
{
echo "$(($1 >> 24 & 255)).$(($1 >> 16 & 255)).$(($1 >> 8 & 255)).$(($1 & 255))"
}
START_NUM=$(ip_to_int $IP_START)
END_NUM=$(ip_to_int $IP_END)
# Begin the Netplan configuration
echo "network:" > /etc/netplan/99-static-ip-config.yaml
echo " version: 2" >> /etc/netplan/99-static-ip-config.yaml
echo " renderer: networkd" >> /etc/netplan/99-static-ip-config.yaml
echo " ethernets:" >> /etc/netplan/99-static-ip-config.yaml
echo " $INTERFACE:" >> /etc/netplan/99-static-ip-config.yaml
echo " addresses:" >> /etc/netplan/99-static-ip-config.yaml
for NUM in $(seq $START_NUM $END_NUM); do
IP=$(int_to_ip $NUM)
echo " - $IP/24" >> /etc/netplan/99-static-ip-config.yaml
done
# Apply the Netplan configuration
netplan apply
echo "All IPs added successfully!"
```
为脚本赋予权限并执行:
```bash
chmod +x add_ips_ubuntu2004.sh
./add_ips_ubuntu2004.sh 192.168.1.10 192.168.1.20
```
此脚本会在 `ens33` 接口上为 IP 地址 `192.168.1.10` 到 `192.168.1.20` 配置静态地址。
注意事项:
1. 执行脚本前,请确保备份 `/etc/netplan` 目录下的所有文件。
2. 根据实际使用的网络接口名称修改脚本中的 `INTERFACE` 变量。
3. 默认子网掩码为 `/24`(也即 `255.255.255.0`)。如需更改,请在脚本中进行相应修改。