Python网卡绑定脚本

前天写了一篇,发现有很多问题,今天吧自己发现问题的地方都给修改后,在自己的虚拟机上面进行测试,至少目前没有发现任何问
题,所以吧前一篇给删除了,现在重新写一篇,只是工作需要所以自己摸索的,再次申明我不是大神,是菜鸟。
这个脚本在linux系统里面可以对各种脚本进行双网卡绑定(仅仅只能两两绑定),如果各位看客要三个,四个网口一起绑定的话,这
脚本满足不了你的需求。绑定的类型是主备的,所以如果是需要冗余,负载等类型的,可以修改os.popen()的内容。废话不多说,
下面上脚本源代码。

# !/usr/bin/python
# -*- coding:utf-8 -*-

import os
import os.path
import re
import time

dir1 = "/etc/sysconfig/network-scripts/"  # 定义路径

# 获取Python的版本号,如果是版本3则返回0 否则返回1
py_ver_num = 0  # 定义变量 表示版本号 0代表版本超过3版本 否则表示低于3版本
python_version = os.popen("python -V").readlines() # 获取Python的版本
if len(python_version) <= 0:  # 如果长度小于0说明Python版本低于3
   py_ver_num = 1
else:
   #  把list转换成str并且截取后转换成int
   str_version = int(str(python_version)[9:10])
   if int_servion < 3:  # 判断版本是多少
      py_ver_num = 1

#  查询文件夹下面所有的网口
def Get_prot():
   net_list = []  # 定义存放网口的list
   for x in os.listdir(dir1):  # 循环查询出来这个路径下面有多少文件
      files = "%s/%s"% (dir1, x)
      # 判断是否是文件并且正则表达式匹配以ifcfg-开头数字结束的字符串
      if os.path.isfile(files) and re.search("^ifcfg-.*?[0-9]$", x):
         net_list.append(x)  # 吧匹配出来的文件添加到list
   return net_list

# 用正则表达式找出存在的bong
def Is_bond():
   list1 = [] # 0 表示已经存在的绑定 1 表示已经做过绑定的网口 2表示未做过绑定的网口
   bond_list = [] # 吧存在的bond放在bond_list中
   eth_list_yes = [] # 吧已经做过绑定的网口找出来
   eth_list_no = [] # 吧没有做过的绑定的网口放在这里面
   for x in Get_prot():
      if re.search("^bond", str(x[6:])):
         bond_list.append(x)
   for x in Get_prot():
      if not re.search("^bond", str(x[6:])):
         with open("%s%s" % (dir1, x), "r") as file:
            flage = 1 # 定义变量 1 表示没做过绑定,0 表示做过绑定
            for line in file:
               if re.search("^SLAVE=yes", line):
                  flage = 0
            if flage == 0:
               eth_list_yes.append(x)
            else:
               eth_list_no.append(x)
   bond_list.sort()      
   eth_list_yes.sort()
   eth_list_no.sort() # key=lambda x: x[net_eth_name()[0]:]
   list1.append(bond_list)
   list1.append(eth_list_yes)
   list1.append(eth_list_no)
   return list1   


# 判断输入的bond名字是否正确
def bond_name(bondname):
   if bondname == "":
      print("绑定名不能为空")
      return 0
   if not bondname.isdigit():
      print("绑定名必须是纯数字")
      return 0
   for x in Is_bond()[0]:
      if bondname == x[10:]:
         print("绑定名已经存在")
         return 0

# 判断输入的ip是否正确 0 表示ip 1表示网关
def net_name(netname, num):
   ip1 = ["255", "255", "255", 255]
   if num == 0:
      if netname == "":
         print("ip不能为空")
                   return 0
           cut_ip = netname.strip().split(".")
      if len(cut_ip) != 4:
         print("你输入的ip不正确")
         return 0
      for x in range(len(ip1)):
         if not cut_ip[x].isdigit():
            print("请不要随便乱输入")
            return 0
         if int(cut_ip[x]) > int(ip1[x]):        
                                print("您输入的ip不正确")
                                return 0
   else:
      if netname != "":
         cut_gw = netname.strip().split(".")
                   if len(cut_gw) != 4:
                           print("你输入的网关不正确")
                           return 0
                   for x in range(len(ip1)):
            if not cut_gw[x].isdigit():
               print("请不要随便乱输入")
               return 0
                           if int(netname.strip().split(".")[x]) > int(ip1[x]):
                                   print("您输入的网关不正确")
                                   return 0
      else:
         return 1   

# 判断网关输入的是否正确
def gw_name(ipname, gwname):
   if net_name(gwname, 1) == 0:
      return 0
   elif net_name(gwname, 1) != 1:
      cut_ip = ipname.split(".")
      cut_gw = gwname.split(".")
      for x in range(4):
         if (x < 3) and (int(cut_ip[x]) != int(cut_gw[x])):
            print("您输入的网关不太正确哦") 
            return 0

# 获取网口名字
def net_eth_name():
        eth_name = ""
        num = 0
   name_list = []
        for x in range(len(Is_bond()[2][0])):
      str_eth = str(Is_bond()[2][0])[x]
      if str_eth.isdigit():  
         num = x
         break           
        eth_name = str(Is_bond()[2][0])[6:num]
   name_list.append(num)
   name_list.append(eth_name)
   return name_list

# 判断网口输入是否正确 num =0 表示主 =1 表示备
def eth_name(ethname, num):
   eth_yes =[] # 已做绑定网口
   eth_no = [] # 未做绑定网口
   if ethname == "":
      if num == 0:
         print("主网口不能为空")
         return 0
      else:
         print("备网口不能为空")
         return 0
   if not ethname.isdigit():
      print("请输入数字")
      return 0

   for x in Is_bond()[1]:
      eth_yes.append(x[net_eth_name()[0]:])
   for x in Is_bond()[2]:
      eth_no.append(x[net_eth_name()[0]:])
   iseth = 0 # 定义变量确定输入的网口是否在为绑定的网口里面
   for x in range(len(eth_no)):
      # 如果输入的网口在未绑定的里面 iseth就为1
      if int(eth_no[x]) == int(ethname):
         iseth = 1
   if iseth == 0:
      iseth1 = 0 
      for x in range(len(eth_yes)):
         if int(eth_yes[x]) == int(ethname):
            iseth1 = 1
      if iseth1 == 0:
         print("对不起,你输入的网口不存在")
         return 0
      else:
         print("此网口已做过绑定")
         return 0
   return str(ethname)

#  修改网口文件
def update_eth(eth, ethname, bondname, bondethname):
   file_data = ""
        line_list = []
        with open("%sifcfg-%s%s" % (dir1, ethname, eth), "r") as files:  # 打开指定文件
                for line in files:  # 循环读取文件内容(按行)
                        line_list.append(line)  # 把找到的内容 添加到一个list
        for x in line_list:  # 循环list 把内容一行行的读取出来
                if re.search('^ONBOOT', x):  # 正则表达式查询是否有ONBOOT开头或结尾的内容
                        file_data += "ONBOOT=yes\n"  # 如果有 则替换这条内容添加到字符串
                elif re.search('^BOOTPROTO', x):
                        file_data += "BOOTPROTO=none\n"
                elif re.search("^NM_CONTROLLED", x):
                        file_data += "NM_CONTROLLED=no\n"
                elif re.search("^UUID", x):
                        file_data += "# %s" % x
      elif re.search("^IPADDR", x):
                        file_data += "# %s" % x
      elif re.search("^NETMASK", x):
                        file_data += "# %s" % x
      elif re.search("^GATEWAY", x):
                        file_data += "# %s" % x
      elif re.search("DNS", x):
                        file_data += "# %s" % x
                else:
                        file_data += x  # 其它内容原封不动添加到字符串         
        #with open("%sifcfg-%s%s" % (dir1, ethname, eth), "w") as file:  # 打开指定文件
        #        file.write(file_data)  # 把修改后的内容全部写到源文件中
   file_data = file_data.strip()
   os.system('echo "%s">%s' % (file_data, bondethname))
        time.sleep(1)
        os.popen('echo "MASTER=bond%s">>%s' % (bondname, bondethname))  # 在源文件后面继续添加内容
        os.popen('echo "SLAVE=yes">>%s' % bondethname)
        print("%s%s修改成功" % (net_eth_name()[1], eth))

# 在开始绑定之前要检查所有未做过绑定的网口的NM_CONTROLLED选项,如果不修改的话,会影响脚本在xshell工具中的使用
for x in Is_bond()[2]:
   print("正在检查%s" % x)
   line_list1 =[]
   file_data1 = ""
   with open("%s%s" % (dir1, x), "r") as files:
      for line in files:
         line_list1.append(line)
   for i in line_list1:
      if re.search("^NM_CONTROLLED", i):
         file_data1 += "NM_CONTROLLED=no\n"
      else:
         file_data1 += i
   file_data1 = file_data1.strip()
        os.system('echo "%s">%s%s' % (file_data1, dir1, x))
        time.sleep(0.5)
print("全部检查完毕,准备开始")

judje = True 
int_while = 0 # 定义变量判断while循环是否完整执行过一次
while judje:
   # 这两行代码很重要,它至少实现了Python2,3版本的输入统一
   if py_ver_num ==1:
      input = raw_input
   print("######################################################################################")
   print("已经存在的绑定:%s" % Is_bond()[0])
   print("已做绑定的网口:%s" % Is_bond()[1])
   print("未做绑定的网口:%s" % Is_bond()[2])
        print("######################################################################################")
   Bond_Name = input("请输入绑定名[例:0,1,2...]:")
   if bond_name(Bond_Name) == 0:
      break
   Bond_Ip = input("请输入绑定IP[例:192.168.1.111]:")
   if net_name(Bond_Ip, 0) == 0:
      break
   Bond_Gw = input("请输入网关不输入表示没有[例:192.168.1.1]:")
   if gw_name(Bond_Ip, Bond_Gw) == 0:
      break
   Zeth_Name = input("请输入绑定主网口[例:0,1,2...]")
   if eth_name(Zeth_Name, 0) == 0:
      break
   Beth_Name = input("请输入绑定备网口[例:0,1,2...]")
   if eth_name(Beth_Name, 1) == 0:
                break
   if eth_name(Beth_Name, 1) == eth_name(Zeth_Name, 0):
      print("主备网口不能一样")
      break

   Bond_Dir = "%sifcfg-bond%s" % (dir1, Bond_Name)
   Bond_Zeth_Name = "%sifcfg-%s%s" % (dir1, net_eth_name()[1], Zeth_Name)
   Bond_Beth_Name = "%sifcfg-%s%s" % (dir1, net_eth_name()[1], Beth_Name)
   os.popen("touch %s" % Bond_Dir)
   time.sleep(1)
   os.popen('echo "DEVICE=bond%s">%s' % (Bond_Name, Bond_Dir))
   os.popen('echo "BOOTPROTO=static">>%s' % Bond_Dir)
   os.popen('echo "TYPE=Ethernet">>%s' % Bond_Dir)
   os.popen('echo "ONBOOT=yes">>%s' % Bond_Dir)
   os.popen('echo "IPADDR=%s">>%s' % (Bond_Ip, Bond_Dir))
   os.popen('echo "NETMASK=255.255.255.0">>%s' % Bond_Dir)
   if Bond_Gw != "":
      os.popen('echo "GATEWAY=%s">>%s' % (Bond_Gw, Bond_Dir))
   os.popen("echo 'BONDING_OPTS=\"primary=%s%s mode=1 miimon=200\" '>>%s" % (net_eth_name()[1], Zeth_Name, Bond_Dir))
   os.popen('echo "# bond name:bond%s">>%s' % (Bond_Name, Bond_Dir))
   os.popen('echo "# net prot:%s%s,%s%s">>%s' % (net_eth_name()[1], Zeth_Name, net_eth_name()[1], Beth_Name, Bond_Dir))
   time.sleep(1)
   print("bond%s创建成功" % Bond_Name)
   ########################################################## 主网口
   update_eth(Zeth_Name, net_eth_name()[1], Bond_Name, Bond_Zeth_Name)
   ########################################################## 备网口
   update_eth(Beth_Name, net_eth_name()[1], Bond_Name, Bond_Beth_Name)
   int_while += 1
   flag = input("是否继续(Y/N):")
   if flag == "Y" or flag == "y":   #如果输入的是“Y”或“y”则继续下一次,其余的则退出
      pass
   else:
      judje = False

   if int_while > 0:
      restart = input("是否重启network(Y/N):")
      if restart == "Y" or restart == "y":  # 如果输入Y/y则重启网络服务
         os.popen("service network restart")
 
 

                
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值