python做一个linux网卡,利用Python 程序实现Linux 网卡 bonding 实现

#!/usr/bin/env python

import os,sys,time,re,shutil

import socket

import fcntl

import struct

import traceback

import commands

#Get interface name

interface_path = '/etc/sysconfig/network-scripts/'

def LOG(info):

""" Log files ...."""

logfile = '/root/pxe_install.log'

files = open(logfile,'a')

try:

files.write('%s : %s \n'%(time.ctime(),info))

except IOError:

files.close()

files.close()

def get_interface ():

os.chdir(interface_path)

eth  = em = list()

for inter in os.listdir(interface_path):

if inter[0:-1] == 'ifcfg-em':

if inter == 'ifcfg-em1' or inter == 'ifcfg-em2':

em.append(inter)

elif inter[0:-1] == 'ifcfg-eth':

if inter == 'ifcfg-eth0' or inter == 'ifcfg-eth1':

eth.append(inter)

if eth:

LOG("Getting interface file name %s is Ok" %eth)

return eth

else:

LOG("Getting interface file name %s is Ok" %em)

return em

def main():

net_name = get_interface()

ipaddr = str()

for inter in net_name:

try:

shutil.move(inter,'/opt/' + inter+'.bak')

_interface_config(inter)

new_interface = inter.split('-')[-1]

if _configure_bond(new_interface):

_configure_bond(new_interface)

LOG("bond script init is Ok")

except Exception,e:

LOG(traceback.format_exc())

if _interface_modprobe():

_interface_modprobe()

if _rester_network():

_rester_network()

# Set interface eth* or em*

def _interface_config(interface):

"""

DEVICE=eth0

BOOTPROTO=static

NOBOOT=yes

NM_CONTROLLED=no

MASTER=bond0

SLAVE=yes

"""

fp = open(interface,'w')

new_interface = interface.split('-')[-1]

if interface == 'ifcfg-em1':

fp.write('DEVICE=%s \n'%new_interface)

fp.write('BOOTPROTO=static \n')

fp.write('ONBOOT=yes \n')

fp.write('NM_CONTROLLED=no \n')

fp.write('MASTER=bond0 \n')

fp.write('SLAVE=yes \n')

elif interface == 'ifcfg-em2':

fp.write('DEVICE=%s \n'%new_interface)

fp.write('BOOTPROTO=static \n')

fp.write('ONBOOT=yes \n')

fp.write('NM_CONTROLLED=no \n')

fp.write('MASTER=bond0 \n')

fp.write('SLAVE=yes \n')

elif interface == 'ifcfg-eth0':

fp.write('DEVICE=%s \n'%new_interface)

fp.write('BOOTPROTO=static \n')

fp.write('ONBOOT=yes \n')

fp.write('NM_CONTROLLED=no \n')

fp.write('MASTER=bond0 \n')

fp.write('SLAVE=yes \n')

elif interface == 'ifcfg-eth1':

fp.write('DEVICE=%s \n'%new_interface)

fp.write('BOOTPROTO=static \n')

fp.write('ONBOOT=yes \n')

fp.write('NM_CONTROLLED=no \n')

fp.write('MASTER=bond0 \n')

fp.write('SLAVE=yes \n')

fp.close()

def _configure_bond(inter):

"""

DEVICE=bond0

BOOTPROTO=static

ONBOOT=yes

IPADDR=192.168.0.100

NETMASK=255.255.255.0

NETWORK=192.168.0.0

BROADCAST=192.168.0.255

"""

#bond name message

if inter == 'eth0':

bond_name = 'ifcfg-bond0'

elif inter == 'em1':

bond_name =  'ifcfg-bond0'

elif inter == 'eth1':

bond_name = 'ifcfg-bond0'

elif inter == 'em2':

bond_name = 'ifcfg-bond0'

# ip address message

if _interface_get_ip(inter):

ipaddr  = _interface_get_ip(inter)

else:

ipaddr = '0.0.0.0'

# ip net mask info

try:

net_mk  = os.popen('ip a |grep %s|grep inet' %inter).readlines()[0]

res = net_mk.split()[1]

net_masklen = res.split('/')[-1]

except:

net_masklen = 18

net_mask = _interface_sum_master(net_masklen)

# default gateway is ....

try:

net_gate = os.popen('ip route |grep default').readlines()[0]

net_gateway = net_gate = net_gate.split(' ')[2]

except:

net_gateway = '0.0.0.0'

try:

if ipaddr == '0.0.0.0':

return ''

fp = open(bond_name,'w')

bond = bond_name.split('-')[-1]

fp.write("DEVICE=%s \n" %bond)

fp.write("BOOTPROTO=static \n")

fp.write("ONBOOT=yes \n")

fp.write("IPADDR=%s \n" %ipaddr)

fp.write("NETMASK=%s \n" % net_mask)

if bond == 'bond0':

fp.write("GATEWAY=%s \n" % net_gateway)

fp.write("DNS1=202.106.0.20 \n")

fp.write("DNS2=8.8.8.8 \n")

LOG("ifcfg-bond* configure is Ok")

return True

except Exception,e:

return False

def _interface_get_ip(inter):

try:

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

IP = socket.inet_ntoa(fcntl.ioctl(

s.fileno(),

0x8915,  # SIOCGIFADDR

struct.pack('24s',inter))[20:24])

return  IP

except Exception,e:

pass

return

# Add modprobe bonding model

def _interface_modprobe():

try:

fp = open('/etc/modprobe.d/bonding.conf','w')

fp.write("#Module options and blacklists written by bonding \n")

fp.write("alias bond0 bonding \n")

fp.write("options bond0 miimon=100 mode=1 \n")

fp.close()

x,y  = commands.getstatusoutput('modprobe bonding')

if x != 0:

LOG("modprobe bonding is failed")

return True

except:

LOG(traceback.format_exc())

return

# Restart Network

def _rester_network():

x,y  = commands.getstatusoutput('service network restart')

if x == 0:

LOG("restart netowrk is Ok ")

return True

else:

LOG("restart netowrk is Faild ")

return

# According to the CIDR calculation.net master

def _interface_sum_master(net_master):

mask =  (2** 8) - 2 ** (24 - int(net_master))

return '255.255.%s.0' % mask

if __name__  == "__main__":

sc = main()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值