Как изменить мой сценарий, чтобы заменить и добавить новую переменную в конфигурации?

Проверьте Вас конфигурация сервера VNC и makesure, для которого номер порта, который Вы даете, 5900+Number seesions, дают пользователю.. Это число Вы дали бы на странице конфигурации Вашего сервера VNC. Если Вы дали число как 2, то номер порта необходимо определить 5902.

Попробуйте это. это могло бы иметь мало справки.

2
22.07.2014, 15:49
2 ответа

Я бы, вероятно, сделал что-то вроде этого:

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()

См. Комментарии в коде. Это разделяет строку конфигурации, изменяет значение, если ключ существует в dict, и, наконец, повторно подтверждает строку для печати в выходной файл. Это также позволяет оставлять комментарии в конце строки.

2
27.01.2020, 22:06

Несколько комментариев по поводу вашего кода:

  1. Если вы хотите легко вставить конфигурацию из «замен», если она не существует, рассмотрите возможность повторения каждой «замены» по строкам файла вместо каждой строки файла поверх «замены». Таким образом, если вы не найдете заменяющего ключа в строках, создайте и напишите новую строку конфигурации.
  2. Я бы предпочел использовать readlines () и закрыть sysctl.conf, чтобы освободить файл sysctl.conf, вместо того, чтобы держать его открытым. Если другие процессы используют sysctl, пока вы его выполняете, это может повредить ваши конфигурации.
  3. Вы анализируете файл sysctl.conf, который содержит строки, начинающиеся с символа «#» или как ключ = значение. нет комментариев после того, как значения существуют.
1
27.01.2020, 22:06

Теги

Похожие вопросы