使用Python修改ifcfg-eth0文件

    def UpdateNetConf(cls, conf):
        ifname = conf['device']
        configmode = conf['configmode']
        try:
            f = open("/etc/sysconfig/network-scripts/ifcfg-%s"%ifname, 'r')
            lines = f.readlines()
            f.close()

            # remove old config
            num=0
            numlist=[]
            tmp=[]
            for line in lines:
                num = num + 1
                if not line.startswith('#'):
                    start=line.split('=')[0].strip().upper()
                    if start!='TYPE' and start!='DEVICE' and start!='ONBOOT':
                        numlist.append(num)
            for i in range(len(numlist)):
                tmp.append(lines[numlist[i]-1])
            lines=list(set(lines)-set(tmp))
            commands.getstatusoutput("echo numlistbianlisuccess >> /tmp/debug.log")
            # append new config
            if configmode.lower() == "static":
                lines.append("BOOTPROTO=\"static\"\n")
                lines.append("IPADDR=%s\n" % conf['ipaddr'])
                lines.append("NETMASK=%s\n" % conf['netmask'])
                lines.append('GATEWAY=%s\n' % conf['gateway'])
            else:
                lines.append("BOOTPROTO=\"dhcp\"\n")

            f = open("/etc/sysconfig/network-scripts/ifcfg-%s"%ifname, 'w')
            for line in lines:
                f.write(line)
            f.close()
            commands.getstatusoutput("echo writesuccess >> /tmp/debug.log")
        except Exception, e:
            raise

      这里只贴出UpdateNetConf函数内容,其与参数在其它函数内部。通过辨别传入的cofigmode为static还是dhcp来修改ifcfg-eth0,dhcp为自动,static为静态,ifcfg-eth0的具体内容就不解释了,网上都有。

BOOTPROTO的值我一开始写的大写,重启不了,就改成小写了。。说不清楚到底用大写还是小写,遇到问题都试试,总有好用的

posted @ 2016-08-09 14:45  草莓干123456  阅读(953)  评论(0编辑  收藏  举报