您的位置:首页 > 运维架构 > Linux

利用Python 程序实现Linux 网卡 bonding 实现

2014-09-23 09:17 821 查看
#!/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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux bond modpore netmask