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
Solution 1:
Easy way to connect Wifi without any modules:
import os
classFinder:
def__init__(self, *args, **kwargs):
self.server_name = kwargs['server_name']
self.password = kwargs['password']
self.interface_name = kwargs['interface']
self.main_dict = {}
defrun(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:
returnNoneelse:
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))
defconnection(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 connectionraise Exception()
except:
raise# Not Connectedelse:
returnTrue# Connectedif __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()
Solution 2:
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
Post a Comment for "Simplest Way To Connect Wifi Python"