如何更改我的脚本以在配置中替换和添加新变量?

如何更改我的脚本以在配置中替换和添加新变量?

嗯,这是我的剧本。它是配置我的系统sysctl.conf。

infile = open('sysctl.conf')
outfile = open('sysctl.conf.new', 'w')

replacements = {'Net.ipv4.icmp_echo_ignore_all' :'1',
            'Net.ipv4.icmp_echo_ignore_broadcasts' :'1',
            'Net.ipv4.ip_forward' : '0',
            'Net.ipv4.tcp_syncookies':'1',
            'Net.ipv4.conf.all.rp_filter': '1',
            'Net.ipv4.conf.all.Log.martiansd':'1',
            'Net.ipv4.conf.all.Secure_redirects' : '1',
            'Net.ipv4.conf.all.Send_redirects' : '0',
            'Net.ipv4.conf.all.Accept_Source_Route':  '0',
            'Net.ipv4.conf.all.Accept_redirects':'0',
            'Net.ipv4.tcp_max_syn_backlog': '4096',
            }

for line in infile:
    if '#' in line:
        pass
    elif '=' in line:
        w = line.split('=')
        for var, value in replacements.iteritems():
            if var in w[0]:
                line=line.replace(w[1],value)
    outfile.write(line)
infile.close()
outfile.close()

该脚本运行良好,但有一个问题。如果替换中的任何参数不存在于 sysctl.conf 中,那么它不会将其添加到新的配置文件中。它只会修改我的值中存在的参数。我想在配置中添加所有参数或更改它们(如果它们已经存在)。怎么做?

我知道这应该很容易,但我被困在这里。

答案1

我可能会做这样的事情:

testing = True

if testing: ##################################################################

    infile = '''
key0=0
key1=1
 key1 = 1
key2=2 # comment1
#key3=3
  #key4=4
#key5=5 # comment
  #key6=6 # comment
key7=7

key8 = 8
    '''

    infilelines = infile.split('\n')


    class of():
        def write(self, s):
            print s
        def close(self):
            pass
    outfile = of()

    replacements = {
        'key1' :'11repl',
        'key2' :'22repl',
        'key3' :'33repl',
        'key4' :'44repl',
        'key5' :'55repl',
        'key6' :'66repl',
        }


else: #########################################################################

    # as proposed by csny, only open file quickly
    # (file is closed after with statement)
    with open('sysctl.conf') as infile:
        infilelines = infile.readlines()

    outfile = open('sysctl.conf.new', 'w')

    replacements = {'Net.ipv4.icmp_echo_ignore_all' :'1',
        'Net.ipv4.icmp_echo_ignore_broadcasts' :'1',
        'Net.ipv4.ip_forward' : '0',
        'Net.ipv4.tcp_syncookies':'1',
        'Net.ipv4.conf.all.rp_filter': '1',
        'Net.ipv4.conf.all.Log.martiansd':'1',
        'Net.ipv4.conf.all.Secure_redirects' : '1',
        'Net.ipv4.conf.all.Send_redirects' : '0',
        'Net.ipv4.conf.all.Accept_Source_Route':  '0',
        'Net.ipv4.conf.all.Accept_redirects':'0',
        'Net.ipv4.tcp_max_syn_backlog': '4096',
        }



for line in infilelines:

    # if # at the beginning (neglecting whitespaces): its only a line comment
    # write it directly to outfile and continue with next line
    if len(line.strip())==0 or line.strip()[0] == '#':
        outfile.write(line.strip())
        continue

    # try if this is a properly formated line like: key=val
    try:
        key, val = line.split('=')
        key = key.strip()
        val = val.strip()

    # something stange happend: It was not a proper key=val line
    # dont modify anything, just write the line to the new file
    except ValueError:
        # or comment out outfile.write to delete the strange line
        # from the output config file
        outfile.write(line)
        continue

    # maybe you want to allow line end comments like: key=val # comment?
    # lets try if the value actually contains a comment
    try:
        val, comment = val.split('#')
        comment = '# ' + comment.strip()
        val = val.strip()

    # there is no comment at the end of the line
    # (the val.split() returns only one value and thus the unpacking fails with:
    # ValueError: need more values to unpack)
    except ValueError:
        comment = ''


    # replace the val if the according key in the `replacements` dict
    # with the value stored in the key
    # otherwise don't change anything
    if key in replacements.keys():
        val = replacements[key]

    # put together the new line for the output file
    line = '%s=%s   %s' % (key, val, comment)
    outfile.write(line)

outfile.close()

请参阅代码中的注释。这会将配置行分开,如果字典中存在该键,则更改值,最后重新组合该行以打印到输出文件。这也允许在行结尾处添加注释。

答案2

关于您的代码的一些评论:

  1. 如果您想轻松地从“替换”中插入配置(如果不存在),请考虑在文件的各行上迭代每个“替换”,而不是在“替换”上迭代文件的每一行。这样,如果您在行中找不到任何替换键,请构造并写入新的配置行。
  2. 我宁愿使用“readlines()”并关闭 sysctl.conf 以释放 sysctl.conf 文件,而不是将其保持打开状态。如果其他进程使用 sysctl,当您运行它时,它可能会损害您的配置。
  3. 您正在解析 sysctl.conf 文件,其中包含以“#”开头或作为 key = value 的行。值存在后没有注释。

相关内容