D
D
Dima_kras2019-01-30 16:59:01
linux
Dima_kras, 2019-01-30 16:59:01

How to change the contents of /etc/dhcpcd.conf using Python?

Good afternoon, in the /etc/dhcpcd.conf file, the ip address of Raspberry is statically set, for example:

interface eth0
 
static ip_address=192.168.0.10/24
static routers=192.168.0.1
static domain_name_servers=192.168.0.1

I want to programmatically replace ip in the Python script to get:
interface eth0
 
static ip_address=192.168.0.18
static routers=192.168.0.1
static domain_name_servers=192.168.0.1

How to do it? Just access it as a text file, read, replace and write back? And reload accordingly for the change to take effect.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Drill, 2019-01-30
@Dima_kras

Yes.

Just access it as a text file, read, replace and write back

A
Andrey Taranov, 2019-10-31
@margadon

for example like this:

def file_edit(fname, field, new_value):
    """ edit conf file <field> value to new one """
    if type(fname)     != str | \
       type(field)     != str | \
       type(new_value) != str :
        return False
    """ to do - validate the field mask """
    with open(fname, 'r') as f:
        file = f.read()
    strs = file.split('\n')
    for i, _str in enumerate(strs):
        if field & not "#" in _str:  #don't edit comments
            strs[i] = field + new_value
    out = ''
    for _str in strs:
        out+=_str+'\n'
    with open(fname, 'w') as f:
        f.write(out)
    return True

The difference between this code and any config parsers is that it completely saves comments in the source file.
You do not need to restart the entire raspberry after editing, just restart dhcpcd.service
sudo ip addr flush dev eth0 && sudo systemctl restart dhcpcd.service

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question