I want to edit/create or delete a part of area of my dhcpd.conf file settled in Raspberry Pi.
I want to edit file located at /etc/dhcpcd.conf and if it contains static ip config block, I will update this block, otherwise I want to create this block and I also want to remove this block in some cases without damaging any other part of the file. Therefore, I have to write a function doing that operations in config file. I saw ConfigParser package for that but I could not sure to use it. How can I solve this problem?
I use this kind of solution but it is not reliable and not working. Maybe using ConfigParse will be more clean solution than that.
interface eth0static ip_address=192.168.0.4/24static routers=192.168.0.1static domain_name_servers=192.168.0.1
@staticmethod def change_static_ip(ip_address, routers, dns): conf_file = '/etc/dhcpcd.conf' try: vars = ['interface', 'static ip_address', 'static routers', 'static domain_name_servers'] new_values = ['eth0', ip_address, routers, dns] changes = dict(zip(vars,new_values)) RE = '(('+'|'.join(changes.keys())+')\s*=)[^\r\n]*?(\r?\n|\r)' pat = re.compile(RE) def jojo(mat,dic = changes): return dic[mat.group(2)].join(mat.group(1,3)) with open(conf_file,'rb') as f: content = f.read().decode('utf-8') with open(conf_file,'wb') as f: f.write(pat.sub(jojo,content)) except Exception as ex: logging.exception("IP changing error: %s", ex) finally: pass