import re
import time
def transform(mask):
if mask<= 7:
print(str(mask) + " = netmask = "+ str(256 - 2**(8 - mask)) + ".0.0.0")
#print("netmask = " + str(256 - 2 ** (8 - mask)) + ".0.0.0")
#print(str(256 - 2 ** (8 - mask)) + ".0.0.0")
exp_mask = str(256 - 2 ** (8 - mask)) + ".0.0.0"
#print(exp_mask)
return exp_mask # 用return 否则会返回None
elif 8<=mask<=15:
print(str(mask) + " = netmask = " + "255."+ str(256 - 2 **(16 - mask)) + ".0.0")
#print("netmask = " + "255." + str(256 - 2 ** (16 - mask)) + ".0.0")
#print("255." + str(256 - 2 ** (16 - mask)) + ".0.0")
exp_mask = "255." + str(256 - 2 ** (16 - mask)) + ".0.0"
#print(exp_mask)
return exp_mask
elif 16<=mask<=23:
print(str(mask) + " = netmask = " + "255.255." + str(256 - 2 **(24 - mask)) + ".0")
#print("netmask = " + "255.255." + str(256 - 2 ** (24 - mask)) + ".0")
#print("255.255." + str(256 - 2 ** (24 - mask)) + ".0")
exp_mask = "255.255." + str(256 - 2 ** (24 - mask)) + ".0"
#print(exp_mask)
return exp_mask
elif 24 <= mask <= 32:
print(str(mask) + " = netmask = " + "255.255.255." + str(256 - 2 **int(32 - mask)))
#print("netmask = " + "255.255.255." + str(256 - 2 ** int(32 - mask)))
#print("255.255.255." + str(256 - 2 ** int(32 - mask)))
exp_mask = "255.255.255." + str(256 - 2 ** int(32 - mask))
#print(exp_mask)
return exp_mask
else:
print("mask的范围为0-32,请输入0-32范围内的整数。")
return False
def main():``
time1 = time.strftime('%Y-%m-%d_%H_%M_%S',time.localtime(time.time()))
pattern = re.compile("(\d*.\d*.\d*.\d*)\/(\d*)") #将原IP分成几段,\d表示数字[0-9]
file_name= "extport_" + time1+ ".txt"
exp=open(file_name,"w")
exp.close()
with open("Office365.txt","r") as f:
context=f.readlines()
count = 1
for item in context:
exp1 = open(file_name, "a+")
res1 = pattern.search(item)
print("条目="+str(count))
print(res1[0]) # 输出整个
#print(res1[1]) # 输出/左边数据
mask=int(res1[2]) # 输出/右边数据
#print(mask)
netmask1=str(transform(mask))
exp1.write("ip route-static "+str(res1[1]) + " %s"%netmask1 + " 172.24.200.10 description by_teams" + "\n")
print(res1[1]+" %s" % netmask1)
exp1.close()
count += 1
if name == 'main':
main()
``
效果如下: 条目=1 104.146.128.0/17 17 = netmask = 255.255.128.0 104.146.128.0 255.255.128.0 条目=2 104.210.208.16/29 29 = netmask = 255.255.255.248 104.210.208.16 255.255.255.248