0

I am able to use Python's ConfigParser library to read /etc/sysctl.conf by adding a [dummy] section and overriding ConfigParser's read() method as follows:

class SysctlConfigParser(ConfigParser.ConfigParser):
    def read(self, fn):
        text = open(fn).read()
        contents = StringIO.StringIO("[dummy]\n" + text)
        self.readfp(contents, fn)

Now the tricky part is to write back configuration updates that my python program made, because if I would now call ConfigParser.write() directly then it would add back this [dummy] section as well:

[dummy]
net.netfilter.nf_conntrack_max = 313
net.netfilter.nf_conntrack_expect_max = 640
net.netfilter.nf_conntrack_tcp_timeout_time_wait = 5

Here are my questions:

  1. Is there an elegant way to make ConfigParser not to add this [dummy] section? It seems odd if I would have to open this file again just to remove the first line that contains this dummy section.
  2. Maybe ConfigParser is not the right tool to edit sysctl.conf? If so are there any other Python libraries that would allow to update sysctl.conf in a convenient way from Python?
user389238
  • 1,656
  • 3
  • 19
  • 40

1 Answers1

2

ConfigParser is designed for parsing INI-style configuration files. /etc/sysconf.conf is not this sort of file.

You could use the Augeas bindings for Python if you want a parser that works out-of-the-box:

import augeas

aug = augeas.Augeas()
aug.set('/files/etc/sysctl.conf/net.ipv4.ip_forwarding', '1')
aug.set('/files/etc/sysctl.conf/fs.inotify.max_user_watches', '8192')
aug.save()

The format of the file is pretty trivial (just a collection of <name> = <value> lines with optional comments).

larsks
  • 277,717
  • 41
  • 399
  • 399