使用Python脚本更改网络设置

时间:2018-06-22 09:40:21

标签: python linux python-3.x network-programming subprocess

我正在尝试通过Python脚本连接到其他WiFi网络

我正在使用运行最新版本的Raspbian的Raspberry Pi 3 Model B +。

wpa_supplicant.conf添加新网络

考虑到另一个具有SSID testing和密码testingPassword的网络,我了解到可以通过在终端中执行以下命令来添加新网络:

wpa_passphrase "testing" "testingPassword" | sudo tee -a /etc/wpa_supplicant/wpa_supplicant.conf > /dev/null

所以我想我可以在python中使用子进程库:

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)

但是所有这些操作(在终端中)被输出:

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


------------------
(program exited with code: 0)
Press return to continue

问题

运行python脚本实际上并没有将字符串附加到wpa_supplicant.conf

知道我在做什么错吗?


已解决

@DougieLawson在树莓派论坛上使用subprocess.Popen为我解决了此问题。

请参阅下面的用法:

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()

0 个答案:

没有答案