One day, using Centos7, when discovering the network configuration, the subnet mask needs to be converted manually, because the CENTOS7 network is configured as follows:
NMCLI Connection Enp4s0 Modify Ipv4.methord manual ipv4.address "192.168.1.120/24" Ipv4.gateway "192.168.1.1" Ipv4.dns "2 23.5.5.5 "
A configuration item with no subnet mask. Then, write a function that implements the mutual transformation of the subnet mask and the bit length.
One: The subnet mask is converted to bit length:
# Coding:utf-8 def exchange_mask (mask): # Calculates the number of ' 1 ' in a binary string count_bit = Lambda Bin_str:len ([I for I in Bin_str if I = = ' 1 ']) # The subnet mask for the split string format is a four segment list mask_splited = Mask.split ('. ') # Convert each satin netmask to binary, calculate decimal mask_count = [Count_bit (Bin (int (i))) for I in mask_splited] return sum (mask_count) if __name_ _ = = ' __main__ ': Print exchange_mask (' 255.255.0.0 ')
Second: The bit length is converted to a subnet mask:
#codint = Utf8def Exchange_maskint (mask_int): Bin_arr = [' 0 ' for I in range (+)] for I in range (Mask_int): Bin_arr[i] = ' 1 ' tmpmask = ['. Join (Bin_arr[i * 8:I * 8 + 8]) for I in range (4)] Tmpmask = [Str (Int. (TMPSTR, 2)) for TMPSTR in TMPM Ask] return '. '. Join (tmpmask) if __name__ = = ' __main__ ': Print Exchange_maskint (24)
This article is from the "Black Time" blog, so be sure to keep this source http://blacktime.blog.51cto.com/11722918/1875549
Using Python to convert the subnet mask address to the bit length