这个问题最近在一次采访中被问到。
**问题:**编写一个bash脚本,将给定的子网细分为预定义数量的较小子网。
分割后的IP地址不应被浪费,也就是说,细分的累积应该构成分割后的子网。
每个子网有3个保留的IP地址,主机无法使用:网络、广播、网关。
显示网络/广播地址、主机数量并分配网关。网关应该是划分的子网中第一个可用的IP。示例:
输入:./subnetter.sh 192.168.0.0/24 3
输出:
subnet=192.168.0.0/25 network=192.168.0.0 broadcast=192.168.0.127 gateway=192.168.0.1 hosts=125
subnet=192.168.0.128/26 network=192.168.0.128 broadcast=192.168.0.191 gateway=192.168.0.129 hosts=61
subnet=192.168.0.192/26 network=192.168.0.192 broadcast=192.168.0.255 gateway=192.168.0.193 hosts=61
输入:./subnetter.sh 192.168.0.0/24 4
输出:
subnet=192.168.0.0/26 network=192.168.0.0 broadcast=192.168.0.63 gateway=192.168.0.1 hosts=61
subnet=192.168.0.64/26 network=192.168.0.64 broadcast=192.168.0.127 gateway=192.168.0.65 hosts=61
subnet=192.168.0.128/26 network=192.168.0.128 broadcast=192.168.0.191 gateway=192.168.0.129 hosts=61
subnet=192.168.0.192/26 network=192.168.0.192 broadcast=192.168.0.255 gateway=192.168.0.193 hosts=61
输入:./subnetter.sh 10.55.10.64/28 2
输出:
subnet=10.55.10.64/29 network=10.55.10.64 broadcast=10.55.10.71 gateway=10.55.10.65 hosts=5
subnet=10.55.10.72/29 network=10.55.10.72 broadcast=10.55.10.79 gateway=10.55.10.73 hosts=5
首先,我试图分析使用什么逻辑来划分子网。其次,我试图使用ipcalc
命令来获得输出,但没有运气。
谢谢
3条答案
按热度按时间ngynwnxp1#
下面是bash脚本,我已经尝试过了:应该可以正常工作。该脚本有两个参数,CIDR块和要划分的子网数量。
kcrjzv8t2#
我相信我已经完成了70%的你需要的东西了。因为你使用ipcalc,所以我也使用了类似的二进制。开始的时候,做以下的事情:
如果您有基于RPM的操作系统,则使用yum安装sipcalc,或者根据Linux操作系统的发行版使用apt-get安装sipcalc。
然后编写以下脚本并将其保存为subnetter.sh,并给予其“x”权限,以便可以执行该脚本。
我的脚本的输出:
请注意,第三个参数的要求非常简单,可以简单地使用for循环来完成,我希望你能做到这一点。
您可以使用以下工具来确保输出正确:http://www.subnet-calculator.com/subnet.php?net_class=C
pkbketx93#
我已经通过了上述要求,下面是我已经编程,以实现的结果。
Python代码与上述shell脚本集成,以实现用户预期的结果
下面的代码将为现有子网创建子子网,然后调用shell脚本执行循环操作,并根据用户请求提供记录。
∮ ∮ ∮
代码2
编号
Sample Out from the result ###