Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to connect WiFi python

I would like to connect to my wifi network using python. I know the SSID and the key for the network, and it's encrypted in WPA2 security. I have seen some libraries like wireless and pywifi but the first didn't work and the second was too complicated. What is the simpelest way to connect to wifi? what is the best library/way?

My failed code using wireless library (I've installed it via pip, of course):

from wireless import Wireless

wire = Wireless()
wire.connect(ssid='myhome',password='password')

interpreter output:

Traceback (most recent call last):
File "C:/Users/Aviv/PycharmProjects/Networks/WiFi/1/1.py", line 4, in 
<module>
wire = Wireless()
File "C:\Python27\lib\site-packages\wireless\Wireless.py", line 23, in 
__init__
self._driver_name = self._detectDriver()
File "C:\Python27\lib\site-packages\wireless\Wireless.py", line 50, in 
_detectDriver
compare = self.vercmp(ver, "0.9.9.0")
File "C:\Python27\lib\site-packages\wireless\Wireless.py", line 71, in vercmp
return cmp(normalize(actual), normalize(test))
File "C:\Python27\lib\site-packages\wireless\Wireless.py", line 70, in 
normalize
return [int(x) for x in re.sub(r'(\.0+)*$', '', v).split(".")]
ValueError: invalid literal for int() with base 10: 'file'
like image 368
A.naam Avatar asked Feb 01 '19 12:02

A.naam


People also ask

Can I hack wifi using Python?

Pywifi → This module provides a cross-platform Python module for manipulating wireless interfaces. Wifi profiles are saved in xml format in our computers and also their is a procedure which we need to follow in order to add new profiles and connect to any profile.


2 Answers

Easy way to connect Wifi without any modules:

import os


class Finder:
    def __init__(self, *args, **kwargs):
        self.server_name = kwargs['server_name']
        self.password = kwargs['password']
        self.interface_name = kwargs['interface']
        self.main_dict = {}

    def run(self):
        command = """sudo iwlist wlp2s0 scan | grep -ioE 'ssid:"(.*{}.*)'"""
        result = os.popen(command.format(self.server_name))
        result = list(result)

        if "Device or resource busy" in result:
                return None
        else:
            ssid_list = [item.lstrip('SSID:').strip('"\n') for item in result]
            print("Successfully get ssids {}".format(str(ssid_list)))

        for name in ssid_list:
            try:
                result = self.connection(name)
            except Exception as exp:
                print("Couldn't connect to name : {}. {}".format(name, exp))
            else:
                if result:
                    print("Successfully connected to {}".format(name))

    def connection(self, name):
        cmd = "nmcli d wifi connect {} password {} iface {}".format(name,
            self.password,
            self.interface_name)
        try:
            if os.system(cmd) != 0: # This will run the command and check connection
                raise Exception()
        except:
            raise # Not Connected
        else:
            return True # Connected

if __name__ == "__main__":
    # Server_name is a case insensitive string, and/or regex pattern which demonstrates
    # the name of targeted WIFI device or a unique part of it.
    server_name = "example_name"
    password = "your_password"
    interface_name = "your_interface_name" # i. e wlp2s0  
    F = Finder(server_name=server_name,
               password=password,
               interface=interface_name)
    F.run()
like image 116
Smack Alpha Avatar answered Oct 21 '22 21:10

Smack Alpha


I hope you are using a windows machine. Then you should install winwifi module. Before installing the winwifi module, it is better to install plumbum module . Try it install in python 32 bit version.

Click this to install plumbum module: https://pypi.org/project/plumbum/

Then install winwifi :https://pypi.org/project/winwifi/

Now you could try connecting a known wifi using the following code:

import winwifi
winwifi.WinWiFi.connect('ssid_of_the_router')

This module has many more commands like:

winwifi.WinWiFi.disconnect()

winwifi.WinWiFi.addprofile('ssid_of_new_router'), etc.

You can check this by exploring my github repository: https://github.com/ashiq-firoz/winwifi_Guide

like image 37
Ashiq Firoz Avatar answered Oct 21 '22 22:10

Ashiq Firoz