Ubuntu 18.04 LTS 批量永久添加 IP 地址

system

Ubuntu 18.04 LTS 批量永久添加 IP 地址

2023-10-26 06:22


                                            




在 Ubuntu 18.04 LTS 中,网络管理主要是由 `Netplan` 处理的。

 

首先,这个脚本会为您的接口添加一个新的 `Netplan` 配置文件。请注意,在使用这个脚本之前,先确认 `/etc/netplan` 目录下的文件情况。

 

脚本名称:`add_ips_ubuntu1804.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)

 

# Preparing YAML configuration for netplan

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_ubuntu1804.sh

./add_ips_ubuntu1804.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`)。如需更改,请在脚本中进行相应修改。