linux新增策略路由python指令碼(待完善)

zzyu發表於2020-05-27
#! _*_ coding:utf-8 _*_
import os,sys,re,fileinput,socket
device_list = []
ip_list = []
ip_end = []
end_ip = []
gw = []
def warning():
print("\033[31;1m注意:指令碼目前不完善,請確認ifconfig網路卡資訊,不要有多餘的網路卡,如(docker0等),可能會導致錯誤!!!\033[0m")
user_input = input("是否以確認ifconfig資訊(y or n):")
if user_input == "y":
pass
elif user_input == "n":
exit()
else:
exit()
warning()
def test_1(func):
def bashrc_file(*args,**kwargs):
func()
dic = dict(map(lambda x,y:[x,y],end_ip,device_list))
dic_2 = dict(map(lambda x,y:[x,y],ip_end,device_list))
with open("/root/.bashrc","a+") as file:
for ip_2,device_2 in dic_2.items():
os.system("echo 'ip route flush table %s' >> /root/.bashrc"%device_2)
for gw_1 in gw:
dic_3 = dict(map(lambda x,y:[x,y],gw_1,device_list))
for k,v in dic_3.items():
os.system("echo 'ip route ad default via %s dev %s table %s' >> /root/.bashrc"%(k,v,v))
for j,i in dic_2.items():
os.system("echo 'ip rule ad from %s table %s' >> /root/.bashrc"%(j,i))
return bashrc_file
 
@test_1
def readDevice():
os.system("ifconfig >> /root/ifconfig.conf")
for num in range(50):
with open("/root/ifconfig.conf","r") as file:
for line in file:
if "eth%s: "%num in line:
a = line.strip().split(":")
a_list = []
a_list.append(a[0])
for loop in a_list:
device_list.append(loop)
 
with open("/root/ifconfig.conf","r") as file:
for line in file:
result = re.findall('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}',line)
if not result == []:
IP_list = []
IP_list.append(result[0])
for loop_1 in IP_list:
ip_list.append(loop_1)
ip_end.append(loop_1)
for i in ip_end:
end_ip.append(i.split(".")[3])
 
ip_list.remove("127.0.0.1")
end_ip.remove("1")
ip_end.remove("127.0.0.1")
 
dic = dict(map(lambda x,y:[x,y],end_ip,device_list))
dic_2 = dict(map(lambda x,y:[x,y],ip_end,device_list))
 
for k,v in dic.items():
os.system("echo %s %s >> /etc/iproute2/rt_tables"%(k,v))
 
for route_flush in device_list:
os.system("ip route flush table %s"%route_flush)
 
user_input_gw = input("請按網路卡順序新增閘道器(以空格分割):").split(" ")
gw.append(user_input_gw)
for i in gw:
dic_gw = dict(map(lambda x,y:[x,y] ,i,device_list))
for k,v in dic_gw.items():
os.system("ip route add default via %s dev %s table %s"%(k,v,v))
 
for ip_1,device_1 in dic_2.items():
os.system("ip rule add from %s table %s"%(ip_1,device_1))
 
os.system("rm -rf ifconfig.conf")
readDevice()
 

相關文章