python script for RaspberryPi to connect wifi automatically

Viewed 46612

I want to operate a WiFi dongle with RaspberryPi, (it's like a CPU without built-in WiFi). I need to write a python script which automatically scan for WiFi networks and a connection need to be automatically established with known SSID and password.

This mean that I need to provide the password for the WiFi network from a file, and the remaining thing is to do the scanning and connecting automatically.

I read a file from the Web which contains WiFi SSID name and password.

I need to write a script which scan and list current networds and match it to the SSID from the file and further to automatically create the connection to this known network.

RaspberryPi OS: Rasbian

4 Answers

You can use the natively available network manager cli package (nmcli):

import subprocess

def what_wifi():
    process = subprocess.run(['nmcli', '-t', '-f', 'ACTIVE,SSID', 'dev', 'wifi'], stdout=subprocess.PIPE)
    if process.returncode == 0:
        return process.stdout.decode('utf-8').strip().split(':')[1]
    else:
        return ''

def is_connected_to(ssid: str):
    return what_wifi() == ssid

def scan_wifi():
    process = subprocess.run(['nmcli', '-t', '-f', 'SSID,SECURITY,SIGNAL', 'dev', 'wifi'], stdout=subprocess.PIPE)
    if process.returncode == 0:
        return process.stdout.decode('utf-8').strip().split('\n')
    else:
        return []
        
def is_wifi_available(ssid: str):
    return ssid in [x.split(':')[0] for x in scan_wifi()]

def connect_to(ssid: str, password: str):
    if not is_wifi_available(ssid):
        return False
    subprocess.call(['nmcli', 'd', 'wifi', 'connect', ssid, 'password', password])
    return is_connected_to(ssid)

def connect_to_saved(ssid: str):
    if not is_wifi_available(ssid):
        return False
    subprocess.call(['nmcli', 'c', 'up', ssid])
    return is_connected_to(ssid)

Connect to a saved network:

connect_to_saved('my_wifi')

Otherwise, connect to a network with ssid and password:

connect_to('my_wifi', 'my_password')

Thank you all for your answers i made simple solution like below

def wifiscan():

   allSSID = Cell.all('wlan0')
   print allSSID # prints all available WIFI SSIDs
   myssid= 'Cell(ssid=vivekHome)' # vivekHome is my wifi name

   for i in range(len(allSSID )):
        if str(allSSID [i]) == myssid:
                a = i
                myssidA = allSSID [a]
                print b
                break
        else:
                print "getout"

   # Creating Scheme with my SSID.
   myssid= Scheme.for_cell('wlan0', 'home', myssidA, 'vivek1234') # vive1234 is the password to my wifi myssidA is the wifi name 

   print myssid
   myssid.save()
   myssid.activate()

wifiscan()   
Related