Skip to content

Instantly share code, notes, and snippets.

@taylor224
Last active February 8, 2024 15:22
Show Gist options
  • Star 40 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save taylor224/516de7dd0b707bc0b1b3 to your computer and use it in GitHub Desktop.
Save taylor224/516de7dd0b707bc0b1b3 to your computer and use it in GitHub Desktop.
Python WiFi Example
# -*- coding: utf-8 -*-
import wifi
def Search():
wifilist = []
cells = wifi.Cell.all('wlan0')
for cell in cells:
wifilist.append(cell)
return wifilist
def FindFromSearchList(ssid):
wifilist = Search()
for cell in wifilist:
if cell.ssid == ssid:
return cell
return False
def FindFromSavedList(ssid):
cell = wifi.Scheme.find('wlan0', ssid)
if cell:
return cell
return False
def Connect(ssid, password=None):
cell = FindFromSearchList(ssid)
if cell:
savedcell = FindFromSavedList(cell.ssid)
# Already Saved from Setting
if savedcell:
savedcell.activate()
return cell
# First time to conenct
else:
if cell.encrypted:
if password:
scheme = Add(cell, password)
try:
scheme.activate()
# Wrong Password
except wifi.exceptions.ConnectionError:
Delete(ssid)
return False
return cell
else:
return False
else:
scheme = Add(cell)
try:
scheme.activate()
except wifi.exceptions.ConnectionError:
Delete(ssid)
return False
return cell
return False
def Add(cell, password=None):
if not cell:
return False
scheme = wifi.Scheme.for_cell('wlan0', cell.ssid, cell, password)
scheme.save()
return scheme
def Delete(ssid):
if not ssid:
return False
cell = FindFromSavedList(ssid)
if cell:
cell.delete()
return True
return False
if __name__ == '__main__':
# Search WiFi and return WiFi list
print Search()
# Connect WiFi with password & without password
print Connect('OpenWiFi')
print Connect('ClosedWiFi', 'password')
# Delete WiFi from auto connect list
print Delete('DeleteWiFi')
@Gariantroll
Copy link

Thanks for the script: I do have a question because of the way I am trying to use this script. I am using the python script as a cgi page. I can't seem to connect to the web from there. The idea is to have users connect to a hotspot through a Raspberry Pi and then they can connect the device to a wifi network via the script on the page. Can you help?

@JeanPierreFig
Copy link

Hey Gariantroll, look at Hotspotd on github it works really well.

@JeanPierreFig
Copy link

hey I am trying to run this script as a module but I am getting Permission denied error when running it I can not use sudo because it is a cgi scrip that is called from a webserver.

@suhasjanardhan
Copy link

thanks for the script: When i try to run the script by taking individual functions I'm getting this error- "Attribute error: Scheme has no attribute ssid". Please help me on this.

@shlomi123
Copy link

what is the wifi is off?

@shlomi123
Copy link

if*

@santhoshbj
Copy link

Sir
I am trying to run this code on my laptop.I am getting error."Couldnot find a version that satisfies the requirement wifi .No matching distribution found for wifi.I tried installing using command line. sudo pip install wifi.failed.please help.thanking you.santhosh.

@dimitrisKarampistis
Copy link

Traceback (most recent call last):
File "WifiModuleLibrary.py", line 101, in
print(Connect('uth-open2'))
File "WifiModuleLibrary.py", line 65, in Connect
scheme.activate()
File "/usr/local/lib/python3.6/dist-packages/wifi/scheme.py", line 173, in activate
ifup_output = subprocess.check_output(['/sbin/ifup'] + self.as_args(), stderr=subprocess.STDOUT)
File "/usr/lib/python3.6/subprocess.py", line 336, in check_output
**kwargs).stdout
File "/usr/lib/python3.6/subprocess.py", line 405, in run
stdout, stderr = process.communicate(input, timeout=timeout)
File "/usr/lib/python3.6/subprocess.py", line 830, in communicate
stdout = self.stdout.read()

@ra7bi
Copy link

ra7bi commented Nov 16, 2018

for all who have a problem with the script , Rename the file from wifi.py to any other name then run the script

@fwperk
Copy link

fwperk commented May 10, 2019

Thanks. Unfortunately, I ran into a problem. I loaded wifi 'pip install wifi' earlier today. The error I got running the module, following the command, is:

python wifi_taylor.py
Traceback (most recent call last):
File "wifi_taylor.py", line 102, in
print Search()
File "wifi_taylor.py", line 9, in Search
cells = wifi.Cell.all('wlan0')
AttributeError: 'module' object has no attribute 'Cell'

Please advise.
Thanks. again.

@fwperk
Copy link

fwperk commented May 10, 2019

I figured out the problem. I had originally saved the module you provided as 'wifi.pi' in the same folder as my execution, so it was importing itself recursively. Removing the module and the compiled code fixed the problem.

@vamsikrishnaA9
Copy link

hi, any body please help
i have struck with the following error when i tried to connect to the Cell(ssid=Vamsi).

[Cell(ssid=SPVF), Cell(ssid=Vamsi), Cell(ssid=Guest), Cell(ssid=ACT_Dlink3Pole)]
Traceback (most recent call last):
File "/home/pi/Desktop/configread.py", line 104, in
print(Connect('Vamsi', '12345678'))
File "/home/pi/Desktop/configread.py", line 49, in Connect
scheme = Add(cell, password)
File "/home/pi/Desktop/configread.py", line 81, in Add
scheme.save()
File "/home/pi/.local/lib/python3.5/site-packages/wifi/scheme.py", line 135, in save
with open(self.interfaces, 'a') as f:
PermissionError: [Errno 13] Permission denied: '/etc/network/interfaces'

@erezfri
Copy link

erezfri commented Sep 22, 2019

Hi,
I'm getting the next error:

Traceback (most recent call last):
File "ConnectWifi.py", line 86, in
print (Connect("stratux"))
File "ConnectWifi.py", line 33, in Connect
savedcell.activate()
File "/usr/local/lib/python3.6/site-packages/wifi/scheme.py", line 172, in activate
subprocess.check_output(['/sbin/ifdown', self.interface], stderr=subprocess.STDOUT)
File "/usr/local/lib/python3.6/subprocess.py", line 336, in check_output
**kwargs).stdout
File "/usr/local/lib/python3.6/subprocess.py", line 418, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['/sbin/ifdown', 'wlan0']' returned non-zero exit status 1

Please help me.

Thanks for the attention, I’m looking forward for any reply.

@Trushtid
Copy link

D:>python wifi.py
Traceback (most recent call last):
File "wifi.py", line 102, in
print Search()
File "wifi.py", line 9, in Search
cells = wifi.Cell.all('wlan0')
AttributeError: 'module' object has no attribute 'Cell'

Why am I getting this error? Cant I use this in windows 10? I am new to python. Please let me know soon. Thanks

@Trushtid
Copy link

What code can i use in windows?

@Frankstar
Copy link

did you install the wifi package?
if not you should probaly "learn python" first before you are using random scripts ...

@initishh
Copy link

I am getting an error like this. wifi.exceptions.InterfaceError: b"wlan0 Interface doesn't support scanning.".
Any help is appreciated.

@sirfrank
Copy link

sirfrank commented Mar 7, 2020

I am getting an error like this. wifi.exceptions.InterfaceError: b"wlan0 Interface doesn't support scanning.".
Any help is appreciated.

run ifconfig , and see ur interface, it is likely not wlan0, but something like wlp2s0

@adityarecogx
Copy link

hi, any body please help
i have struck with the following error when i tried to connect to the Cell(ssid=Vamsi).

[Cell(ssid=SPVF), Cell(ssid=Vamsi), Cell(ssid=Guest), Cell(ssid=ACT_Dlink3Pole)]
Traceback (most recent call last):
File "/home/pi/Desktop/configread.py", line 104, in
print(Connect('Vamsi', '12345678'))
File "/home/pi/Desktop/configread.py", line 49, in Connect
scheme = Add(cell, password)
File "/home/pi/Desktop/configread.py", line 81, in Add
scheme.save()
File "/home/pi/.local/lib/python3.5/site-packages/wifi/scheme.py", line 135, in save
with open(self.interfaces, 'a') as f:
PermissionError: [Errno 13] Permission denied: '/etc/network/interfaces'

Did you find solution for this

@ibelgin
Copy link

ibelgin commented Jul 22, 2020

Struck Here Some Help Please

cells = wifi.Cell.all('wlan0')
Traceback (most recent call last):
File "", line 1, in
File "G:\Python\lib\site-packages\wifi\scan.py", line 38, in all
iwlist_scan = subprocess.check_output(['/sbin/iwlist', interface, 'scan'],
File "G:\Python\lib\subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "G:\Python\lib\subprocess.py", line 489, in run
with Popen(*popenargs, **kwargs) as process:
File "G:\Python\lib\subprocess.py", line 854, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "G:\Python\lib\subprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

@vincentBenet
Copy link

Struck Here Some Help Please

cells = wifi.Cell.all('wlan0')
Traceback (most recent call last):
File "", line 1, in
File "G:\Python\lib\site-packages\wifi\scan.py", line 38, in all
iwlist_scan = subprocess.check_output(['/sbin/iwlist', interface, 'scan'],
File "G:\Python\lib\subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "G:\Python\lib\subprocess.py", line 489, in run
with Popen(*popenargs, **kwargs) as process:
File "G:\Python\lib\subprocess.py", line 854, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "G:\Python\lib\subprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

It is because you are on windows 10.
I am looking for the interface to enter for windows 10 too ...

@X-88
Copy link

X-88 commented Oct 2, 2020

this is needed root access only?
any idea without root access?

@chetanyaag
Copy link

Struck Here Some Help Please

cells = wifi.Cell.all('wlan0')
Traceback (most recent call last):
File "", line 1, in
File "G:\Python\lib\site-packages\wifi\scan.py", line 38, in all
iwlist_scan = subprocess.check_output(['/sbin/iwlist', interface, 'scan'],
File "G:\Python\lib\subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "G:\Python\lib\subprocess.py", line 489, in run
with Popen(*popenargs, **kwargs) as process:
File "G:\Python\lib\subprocess.py", line 854, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "G:\Python\lib\subprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

It is because you are on windows 10.
I am looking for the interface to enter for windows 10 too ...

did you found any solution?

@vincentBenet
Copy link

vincentBenet commented Jul 6, 2021

Struck Here Some Help Please

cells = wifi.Cell.all('wlan0')
Traceback (most recent call last):
File "", line 1, in
File "G:\Python\lib\site-packages\wifi\scan.py", line 38, in all
iwlist_scan = subprocess.check_output(['/sbin/iwlist', interface, 'scan'],
File "G:\Python\lib\subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "G:\Python\lib\subprocess.py", line 489, in run
with Popen(*popenargs, **kwargs) as process:
File "G:\Python\lib\subprocess.py", line 854, in init
self._execute_child(args, executable, preexec_fn, close_fds,
File "G:\Python\lib\subprocess.py", line 1307, in _execute_child
hp, ht, pid, tid = _winapi.CreateProcess(executable, args,
FileNotFoundError: [WinError 2] The system cannot find the file specified

It is because you are on windows 10.
I am looking for the interface to enter for windows 10 too ...

did you found any solution?

Yes:
Here you are (old code that worked a long time ago^^)

import os
from sys import platform
import time
if platform in ["win32", "linux"]:
    import pywifi
    from pywifi import const
import subprocess
import re


def main(ssid, psk, timeout):
    print("Wifi connecting: SSID {0} ".format(ssid))
    if ssid == get_current_wifi():
        print("Wifi already connected to {0}".format(ssid))
        return
    connect_wifi(ssid, psk, int(timeout))


def create_wifi_interface():
    print("Creating wifi interface")
    wifi = pywifi.PyWiFi()
    return wifi.interfaces()[0]


def disconnect_wifi(timeout, interface):
    print("Disconnect wifi")
    interface.disconnect()
    t_0 = time.time()
    while not (interface.status() in [const.IFACE_DISCONNECTED,
                                      const.IFACE_INACTIVE]):
        if time.time() - t_0 > timeout:
            raise TimeoutError
        time.sleep(0.1)
        print(".", end="")
    print("Disconnect wifi succes!")


def connect_wifi(ssid, psk, timeout):
    print("Connect wifi for {0}".format(platform))
    interface = create_wifi_interface()
    disconnect_wifi(timeout, interface)
    profile = pywifi.Profile()
    profile.ssid = ssid
    profile.auth = const.AUTH_ALG_OPEN
    profile.akm.append(const.AKM_TYPE_WPA2PSK)
    profile.cipher = const.CIPHER_TYPE_CCMP
    profile.key = psk
    interface.remove_all_network_profiles()
    tmp_profile = interface.add_network_profile(profile)
    interface.connect(tmp_profile)
    t_0 = time.time()
    while not (interface.status() == const.IFACE_CONNECTED):
        if time.time() - t_0 > timeout:
            raise TimeoutError
        time.sleep(0.1)
        print(".", end="")
    print("\n", "Connect wifi succes!")


def get_current_wifi():
    print("Get current wifi for {0}".format(platform))
    ssid = ""
    if platform == "win32":  # Windows
        try:
            ssid = get_current_wifi_windows()
        except subprocess.CalledProcessError:
            pass
    elif platform == "linux":
        try:
            ssid = get_current_wifi_linux()
        except AttributeError:
            pass
    else:
        raise OSError
    print("Current ssid {0}".format(ssid))
    return ssid


def get_current_wifi_linux():
    network_information = os.popen('/sbin/iwconfig | grep ESSID').read()
    ssid = re.search('ESSID:"(.*)"', network_information).group(1)
    return ssid


def get_current_wifi_windows():
    network_information = str(subprocess.check_output(["netsh", "wlan", "show", "network"]))
    network_information = network_information.replace('\\r', '')
    network_information = network_information.replace("b' ", '')
    network_information = network_information.replace(":", '\n')
    network_information = network_information.replace("\\n", '\n')
    network_information = network_information.splitlines()
    ssid = network_information[6][1:]
    return ssid

To make it work on windows 10 just use:

subprocess.check_output(["netsh", "wlan", "show", "network"])

@chetanyaag
Copy link

chetanyaag commented Jul 6, 2021 via email

@Ganesh-Shanbhag-face
Copy link

Hi, I am getting this error. What may be wrong?

[Cell(ssid=mySSID)]
Traceback (most recent call last):
  File "/home/pi/wifi_con.py", line 89, in <module>
    print(Connect('mySSID', '@key12345'))
  File "/home/pi/wifi_con.py", line 34, in Connect
    savedcell.activate()
  File "/home/pi/.local/lib/python3.9/site-packages/wifi/scheme.py", line 172, in activate
    subprocess.check_output(['/sbin/ifdown', self.interface], stderr=subprocess.STDOUT)
  File "/usr/lib/python3.9/subprocess.py", line 424, in check_output
    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  File "/usr/lib/python3.9/subprocess.py", line 528, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['/sbin/ifdown', 'wlan0']' returned non-zero exit status 1.

@peacekeeperrusev
Copy link

Guys…can you give me pls an answer of this question…my devise is not rooted..
Can this script run without any problems ???

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment