How do you edit wpa_supplicant.conf on a Raspberry Pi in Node JS with sed?

1.4k views Asked by At

My conf file looks like this:

ssid="oldssid"
psk="oldpassword"

I'm using the following code to try and edit my Wifi settings in a Node JS app but it isn't making any changes to the file. Any advice would be much appreciated!

        var ssid_command = "sed -i \'s/ssid=\"oldssid\"/ssid=\"" + newssid + "\"/\' /etc/wpa_supplicant/wpa_supplicant.conf";
        var psk_command = "sed -i \'s/psk=\"oldpassword\"/psk=\"" + newpassword + "\"/\' /etc/wpa_supplicant/wpa_supplicant.conf";
        require('child_process').exec(ssid_command, function (msg) { console.log(msg) });
        require('child_process').exec(psk_command, function (msg) { console.log(msg) });
2

There are 2 answers

0
agniiyer On BEST ANSWER

Turns out all I had to do was add sudo to the beginning so that I have permission to edit the file.

2
Jason Holloway On

If the contents of your conf file look like so...

ssid=oldssid
psk=oldpassword

...then your generated shell command of...

sed -i 's/ssid="oldssid"/ssid="newssid"/' wpa_supplicant.conf

...has one too many levels of quoting.

Everything within the single quote marks is treated by the shell as one uninterrupted, unparsed string, and is passed to sed as such. Sed treats quote marks just as normal characters to match and replace - so the marks around oldssid are sought, and presumably not found because they don't exist in the file.

You want to generate something more like this:

sed -i 's/ssid=oldssid/ssid=newssid/' wpa_supplicant.conf

...which you could do like so...

var command = "sed -i 's/ssid=oldssid/ssid=" + newssid + "/' wpa_supplicant.conf";

PS you also don't need to escape the single quotes within a doubly-quoted string in javascript - though doing so doesn't break anything