zoukankan      html  css  js  c++  java
  • 使用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"
    ")
                    lines.append("IPADDR=%s
    " % conf['ipaddr'])
                    lines.append("NETMASK=%s
    " % conf['netmask'])
                    lines.append('GATEWAY=%s
    ' % conf['gateway'])
                else:
                    lines.append("BOOTPROTO="dhcp"
    ")
    
                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的值我一开始写的大写,重启不了,就改成小写了。。说不清楚到底用大写还是小写,遇到问题都试试,总有好用的

  • 相关阅读:
    备忘录
    中缀表达式转为后缀表达式
    未出现的最小正整数
    摩尔投票算法
    两个等长升序序列找中位数
    Morris二叉树遍历
    2020牛客寒假算法基础集训营5 街机争霸
    2020牛客寒假算法基础集训营5 牛牛战队的比赛地
    2020牛客寒假算法基础集训营2 求函数
    2020牛客寒假算法基础集训营2 建通道
  • 原文地址:https://www.cnblogs.com/chenyaling/p/5753187.html
Copyright © 2011-2022 走看看