0

I want to update a record in the wpa_supplicant.conf file where the passoword for one of the connections is saved. It is supposed to work regardless of whether the whole record sits in just one line or is formatted in a different way. So if "network" is the name of my network basically what I want to do is take

network={ ssid="network" psk="password" }

and substitute

network" (...whatever...) }

with

network" psk="new_password"}

I know the regular expression is a key to that but since I'm completely infamiliar with that I could use a hand.

Thanks in advance

Miki
  • 1
  • 2

1 Answers1

0

You could use simply a solution without regex. Especially for novices in programming, regex could be really badass.

A possible solution without regex would be:

def set_new_password(password):
    with open('/etc/wpa_supplicant/wpa_supplicant.conf','r') as f:
            in_file = f.readlines()
            f.close()

    out_file = []
    for line in in_file:
            if line.startswith("psk"):
                    line = 'psk='+'"'+password+'"'+'\n'
            out_file.append(line)

    with open('/etc/wpa_supplicant/wpa_supplicant.conf','w') as f:
            for line in out_file:
                    f.write(line)

Here is another one with a regex solution. It isn't a very elegant regular expression but maybe with such a easy example you can follow its meaning:

def set_new_password(password):
    with open('/etc/wpa_supplicant/wpa_supplicant.conf','r') as f:
            in_file = f.read()
            f.close()

    out_file =  re.sub(r'psk=".*"','psk='+'"'+password+'"',in_file)

    with open('/etc/wpa_supplicant/wpa_supplicant.conf','w') as f:
            f.write(out_file)
            f.close()

You should have a look at Regex101. There you can check out your ideas for regular expressions very easily.