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的值我一开始写的大写,重启不了,就改成小写了。。说不清楚到底用大写还是小写,遇到问题都试试,总有好用的

  • 相关阅读:
    vue监听多个变量的方法
    Unicode与JavaScript详解
    两个数组合并的方法
    第13章 事件
    第12章 DOM2和DOM3
    IIS发布WebService的一些常见问题
    Openlayers修改矢量要素并且可捕捉
    Openlayers修改矢量要素
    openlayers画图形返回范围
    前台html与后台php通信(上传文件)
  • 原文地址:https://www.cnblogs.com/chenyaling/p/5753187.html
Copyright © 2011-2022 走看看