JonnyNich
JonnyNich

Reputation: 1281

Python console error conditional statement

I'm playing with the os module on python, namely the function which gives you access to the console, and I'm trying to create a sort-of Wi-Fi network sign in tool. This is all done on a Mac, and I'm using the networksetup -setairportnetwork en0 "SSID" password. I was wondering, when a password is wrong, if there was a way for python to respond to that, kind of like a try...except... statement. Here's the current code:

import os
ssid = input("Please enter the network SSID \n")
password = input("Please enter the network password \n")
print ("Connecting to...")
print ("SSID: " + ssid)
print ("Password: " + password)
os.system("networksetup -setairportnetwork en0 \"" + ssid + "\" " + password)

Upvotes: 0

Views: 74

Answers (2)

imolit
imolit

Reputation: 8332

It seems networksetup does not behave well, and returns 0 even on errors. This means you will have to parse the output from the program.

import subprocess
import sys

def networksetup(ssid, password):
    cmd = 'networksetup -setairportnetwork en0 "{}" {}'.format(ssid, password)
    output = subprocess.check_output(cmd.split(), stderr=subprocess.STDOUT)
    return output

def main():
    ssid = input("Please enter the network SSID \n")
    password = input("Please enter the network password \n")
    print ("Connecting to...")
    print ("SSID: " + ssid)
    print ("Password: " + password)
    output = networksetup(ssid, password)
    if 'Error: -3900' in output:
        print("Password error: {}".format(output))
        sys.exit(1)  # remove this if you don't want to exit on error

if __name__ = "__main__":
    main()

Upvotes: 0

Daniel Lee
Daniel Lee

Reputation: 8051

This should work. Change the Exception to catch the exception raised.

import os
success = False
while not success:
    ssid = input("Please enter the network SSID \n")
    password = input("Please enter the network password \n")
    print ("Connecting to...")
    print ("SSID: " + ssid)
    print ("Password: " + password)
    try:
        os.system("networksetup -setairportnetwork en0 \"" + ssid + "\" " + password)
        success = True
    except Exception as e:
        print("verification failed")
        print("Exception: {}".format(e)) 

Upvotes: 1

Related Questions