Debian 多IP 配置

邱秋 • 2024年08月07日 • 阅读:95 • linux debian mult-ip

我有500个IP ,要绑定在同一台linux机器上, OS为debian .

假如这500个IP分为4个C段.

192.168.1.128/25
192.168.2.128/25
192.168.3.128/25
192.168.4.128/25

通过计算我们可以得出 192.168.1.128/25 的网关为192.168.1.129 ,掩码为255.255.255.128,第一个可用IP为192.168.1.130 ,最后一个可用IP为 192.168.1.254 , 那么可用IP为 125个 .

下面的pyhotn 脚本可用计算

import os
import ipaddress
def get_ip(ip: str):
    # demo ip 198.23.190.202/29
    # 定义网络
    network = ipaddress.IPv4Network(ip, strict=False)

    # 计算Netmask
    netmask = network.netmask

    # 计算Network Address
    network_address = network.network_address

    # 计算Broadcast Address
    broadcast_address = network.broadcast_address

    # 计算Gateway Address (通常是网络地址的下一个地址)
    gateway_address = network_address + 1

    # 计算First Usable Address (通常是网络地址的下一个地址)
    first_usable_address = network_address + 1

    # 计算Last Usable Address (广播地址的前一个地址)
    last_usable_address = broadcast_address - 1

    # 计算Usable Addresses
    usable_addresses = list(network.hosts())

    ip_list = list(map(lambda x: str(x), usable_addresses))
    # 第一个是网关, 要干掉
    ip_list.pop(0)

    return {
        "netmask": str(netmask), # 掩码
        "gateway": str(gateway_address), # 网关
        "usable_addresses": ip_list, # 可用IP列表
        "first_usable_address": str(first_usable_address), # 第一个可用IP
        "last_usable_address": str(last_usable_address), # 最后一个可用IP
        "prefix": str(network.prefixlen), #掩码长度
    }

查看网络接口

ip route show

可以看到默认的网口为 eno1:

default via 10x.xx.xx.1 dev eno1 onlink 
10x.xx.xx.0/25 dev eno1 proto kernel scope link src 10x.xx.xx.x 
10x.xx.xx.0/25 dev eno1 proto kernel scope link src 10x.xx.xx.x

假设我们有200台服务器 ,每台服务器要配置500个IP , 那么我们利用脚本计算:

import os
INTERFACE = "eno1"


list_map = {
    "ServerA": [
        '192.168.1.128/25',
    '192.168.2.128/25',
    '192.168.3.128/25',
    '192.168.4.128/25'
    ],
    ...
}

for k in list_map:
    conf_path = os.path.join(os.path.abspath('.'), 'config', f'{k}.conf')

    _list = list_map[k]
    port = 1
    conf = ''
    for ip in _list:
        ips = get_ip(ip)
        ip_list = ips['usable_addresses']
        netmask = ips['netmask']
        for m in ip_list:
            conf += f"auto eno1:{port}\n"
            conf += f"iface eno1:{port} inet static\n"
            conf += f"    address {m}\n"
            conf += f"    netmask {netmask}\n\n"
            port = port+1

    with open(conf_path, 'w') as f:
        f.write(conf)

执行脚本之后 得到 配置文件 ServerA.conf :

auto eno1:1
iface eno1:1 inet static
    address 192.168.1.130
    netmask 255.255.255.128
# 省略...
auto eno1:500
iface eno1:500 inet static
    address 192.168.4.254
    netmask 255.255.255.128

我们把生成的 ServerA.conf 文件 拷贝到 服务器 '/etc/network/interfaces.d' 目录下.

然后重启网络服务即可

sudo service networking restart 
#or 
systemctl restart networking.service
#or 
systemctl restart systemd-networkd

验证配置IP是否生效

hostname -I

此时就能看到我们配置的500个IP.

我,秦始皇,打钱!