mattg31
Posts: 55
Joined: Fri Jan 05, 2018 9:55 pm

changing network settings via python subcommand

Thu Jun 21, 2018 10:49 pm

I am trying to connect to a wifi network via a python script using a Raspberry Pi 3 Model B+, running latest version of raspbian.
I have found that I can do this from the terminal using:

Code: Select all

wpa_passphrase "testing" "testingPassword" | sudo tee -a /etc/wpa_supplicant/wpa_supplicant.conf > /dev/null
So I figured I could use the subprocess library in python:

Code: Select all

import subprocess

ssid = '"testing"'
passkey='"testingPassword"'

command = ["wpa_passphrase", ssid, passkey, "|", "sudo", "tee", "-a", "/etc/wpa_supplicant/wpa_supplicant.conf", ">", "/dev/null"]

subprocess.run(command)
But all this does is output (in the terminal):

Code: Select all

network={
	ssid=""testing""
	#psk=""testingPassword""
	psk=3f446508c00cab57863ae62c8aaa505a4fae5d73461a0f10aee09988be8a2ae6
}


------------------
(program exited with code: 0)
Press return to continue
It does not actually append the string to wpa_supplicant.conf
Any idea what I'm doing wrong?

User avatar
topguy
Posts: 4774
Joined: Tue Oct 09, 2012 11:46 am
Location: Trondheim, Norway

Re: changing network settings via python subcommand

Fri Jun 22, 2018 10:49 am

I have a feeling you need to run the command in a shell to get the piping working.

Code: Select all

subprocess.run(command, shell=True)

mattg31
Posts: 55
Joined: Fri Jan 05, 2018 9:55 pm

Re: changing network settings via python subcommand

Sat Jun 23, 2018 12:56 am

Thanks for the reply. When I run with shell I get:

Code: Select all

usage: wpa_passphrase <ssid> [passphrase]

If passphrase is left out, it will be read from stdin

User avatar
DougieLawson
Posts: 33637
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website

Re: changing network settings via python subcommand

Sat Jun 23, 2018 8:41 am

Code: Select all

import subprocess
ssid="MickeyMouse"
passkey="MinnieMouse"
p1 = subprocess.Popen(["wpa_passphrase", ssid, passkey], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["sudo","tee","-a","/etc/wpa_supplicant/wpa_supplicant.conf",">","/dev/null"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()  # Give p1 a SIGPIPE if p2 dies.
output,err = p2.communicate()
Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

2012-18: 1B*5, 2B*2, B+, A+, Z, ZW, 3Bs*3, 3B+

Any DMs sent on Twitter will be answered next month.

mattg31
Posts: 55
Joined: Fri Jan 05, 2018 9:55 pm

Re: changing network settings via python subcommand

Sat Jun 23, 2018 12:29 pm

@DougieLawson you are the best!
That worked. Thanks!

Return to “Python”

Who is online

Users browsing this forum: No registered users and 7 guests