1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/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:
        = 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 == 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()