0

I'm currently working with RaspberryPi-3 with Rasbian installed. I want to auto-reconnect to a network to a specific network. Going through the internet, I found out a way to do it i.e. by editing the interfaces file under /etc/network. I want to edit this file using some script (preferably Python-3). I just need to add these lines to the interfaces file:

auto wlan0
iface wlan0 inet dhcp
    wpa-ssid <my-SSID>
    wpa-psk <my-PassKey>

Please help me regarding this issue.

4
  • You may find existing answers that will help by searching for things like "python edit file" or "python append lines to file". Commented Jan 22, 2019 at 16:55
  • Possible duplicate of python - edit a text file Commented Jan 22, 2019 at 17:22
  • Whatever you see on configure wi-fi setting on /etc/network is outdated since Debian/Raspian Jessie. The setting should be done via /etc/wpa_supplicant/wpa_supplicant.conf. Commented Feb 3, 2019 at 2:17
  • Furthermore, auto reconnect of wifi can be done via linux system configuration than using python script. Commented Feb 3, 2019 at 2:21

1 Answer 1

0

If you have no specific reason to do that in Python I'd suggest a simple shell script like:

MYSSID=WiFi1
WIFIPW=Zekrett1

cat >> /etc/network/interfaces << EoNet
auto wlan0
iface wlan0 inet dhcp
    wpa-ssid $MYSSID
    wpa-psk  $WIFIPW
EoNet

the same in Python 2/3:

ssid='WiFi1'
wifipw='Zekrett1'

with open('/etc/network/interfaces', 'a') as netcfg:
    netcfg.write('auto wlan0\n'
                 'iface wlan0 inet dhcp\n'
                 '    wpa-ssid {}\n'
                 '    wpa-psk  {}\n'.format(ssid, wifipw))
Sign up to request clarification or add additional context in comments.

1 Comment

There is a small correction though! The path should be /etc/network/interfaces instead of /etc/network

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.