How to connect WiFi using Python?
Last Updated :
23 Aug, 2021
Seeing a computer without an active internet connection today is next to impossible. The Internet has been of the utmost importance in the 21st Century. There are multiple ways one can connect their machine to the Internet. The first being, the traditional cables, i.e. the Ethernet, and the other being, the modern Wireless Fidelity Systems or Wi-Fi as we all know it. Wi-Fi has made life easier and faster for all of us. With a touch of the thumb or a click of the mouse, we get connected to a limitless ocean of information and resources almost instantaneously. In this article, we will accomplish the same task with a High-Level modern programming language, like Python
Connecting to a Known WiFi Network
Here we are going to connect to a previously connected WiFi network.
Approach:
The approach of the program will be simple:
- Import the necessary libraries.
- Displaying all the available SSIDs with the help of cmd commands and a python library named os.
- Selecting the known Wi-Fi you want to connect to.
- Wait for it to Connect successfully.
Now, let's get coding. We will make use of a couple of Windows Command Prompt commands to access the list of available Wi-Fi networks and to connect to a previously connected network. But, how do we write and execute Window Command Prompt commands in a Python script? Umm...
The os library helps us communicate with the operating system directly through python with several methods like path(), getcwd(), system(), etc. We can even run CMD commands using os functions.
Implementation:
Python3
# import module
import os
# scan available Wifi networks
os.system('cmd /c "netsh wlan show networks"')
# input Wifi name
name_of_router = input('Enter Name/SSID of the Wifi Network you wish to connect to: ')
# connect to the given wifi network
os.system(f'''cmd /c "netsh wlan connect name={name_of_router}"''')
print("If you're not yet connected, try connecting to a previously connected SSID again!")
Output:
Explanation:
Here, first, we fetch the os library using the import keyword. Then, we use the system() method from the os library with helps us run the cmd command
'cmd /c "netsh wlan show networks"'
The above command scans all the available SSIDs and displays them as output along with their Infrastructure, Authentication, and Encryption type. We proceed by taking a string input of the SSID, the user wishes to connect to and save them in the variable named, name_of_router.
This string variable is then substituted in the place of another cmd command where we are supposed to enter the name of the SSID.
f'''cmd /c "netsh wlan connect name={name_of_router}"'''
We will now be successfully connected to the particular SSID.
Connecting to a New Wi-Fi Network
Now, connecting to a new Wi-Fi involves a couple of more steps. To connect to a new network, we must first add this new Wi-Fi Network profile to our system using an .XML file. This makes that Wi-Fi network, a known SSID, and we can now successfully connect to it using the above steps.
Approach:
- Step 1: Import the os library
- Step 2: Set up the new Wi-Fi Network's XML configuration
- Step 3: Select the Wi-Fi Network
- Step 4: Add this profile to your system
- Step 5: Connect to the Wi-Fi network
Implementation:
Python3
# import module
import os
# function to establish a new connection
def createNewConnection(name, SSID, password):
config = """<?xml version=\"1.0\"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
<name>"""+name+"""</name>
<SSIDConfig>
<SSID>
<name>"""+SSID+"""</name>
</SSID>
</SSIDConfig>
<connectionType>ESS</connectionType>
<connectionMode>auto</connectionMode>
<MSM>
<security>
<authEncryption>
<authentication>WPA2PSK</authentication>
<encryption>AES</encryption>
<useOneX>false</useOneX>
</authEncryption>
<sharedKey>
<keyType>passPhrase</keyType>
<protected>false</protected>
<keyMaterial>"""+password+"""</keyMaterial>
</sharedKey>
</security>
</MSM>
</WLANProfile>"""
command = "netsh wlan add profile filename=\""+name+".xml\""+" interface=Wi-Fi"
with open(name+".xml", 'w') as file:
file.write(config)
os.system(command)
# function to connect to a network
def connect(name, SSID):
command = "netsh wlan connect name=\""+name+"\" ssid=\""+SSID+"\" interface=Wi-Fi"
os.system(command)
# function to display avavilabe Wifi networks
def displayAvailableNetworks():
command = "netsh wlan show networks interface=Wi-Fi"
os.system(command)
# display available netwroks
displayAvailableNetworks()
# input wifi name and password
name = input("Name of Wi-Fi: ")
password = input("Password: ")
# establish new connection
createNewConnection(name, name, password)
# connect to the wifi network
connect(name, name)
print("If you aren't connected to this network, try connecting with the correct password!")
Output:
Explanation:
First, we define the createNewConnection function which takes the parameters name, SSID, and password, which are all strings that we used to complete to config variable. The config variable is a string that helps us define the XML configuration for a new Wi-Fi Network.
Then, we take the input from the user for the SSID name and Password. They are then fed into XML code which is then added as a profile using the following lines of code:
command = "netsh wlan add profile filename=\""+name+".xml\""+" interface=Wi-Fi"
with open(name+".xml", 'w') as file:
file.write(config)
os.system(command)
We can now connect to the Wi-Fi using the same commands we used earlier in this article and connect to the network as if it was a known one.
Similar Reads
Wi-Fi QR Code Generator Using Python
Prerequisite: Getting Saved Wifi Passwords using Python We know the wireless network is the most common network adapter for today, Because of its supports portability and User friendly. In this article, we will see how we can get the current saved Wi-Fi name and passwords and generate QR code to con
2 min read
Internet of Things with Python
The integration of Python into the Internet of Things (IoT) signifies a transformation in how we develop, implement, and scale IoT applications. Python's simplicity, versatility, and robust library ecosystem make it an excellent choice for IoT development, enabling everything from simple home automa
8 min read
How to Connect Python with SQL Database?
In this article, we will learn how to connect SQL with Python using the MySQL Connector Python module. Below diagram illustrates how a connection request is sent to MySQL connector Python, how it gets accepted from the database and how the cursor is executed with result data.SQL connection with Pyth
2 min read
How to Disconnect Devices from Wi-Fi using Scapy in Python?
Without permission, disconnecting a device from a Wi-Fi network is against the law and immoral. Sometimes, you might need to check your network's security or address network problems. You may send a de-authentication packet to disconnect devices from Wi-Fi using Scapy, a potent Python packet manipul
5 min read
Connect to MySQL using PyMySQL in Python
In this article, we will discuss how to connect to the MySQL database remotely or locally using Python. In below process, we will use PyMySQL module of Python to connect our database. What is PyMySQL? This package contains a pure-Python MySQL client library, based on PEP 249. Requirements : MySQL Se
2 min read
How to Connect Alexa to Wi-Fi?
Setting up your Alexa gadget is direct, and one of the key steps is connecting it to your Wi-Fi network. Alexa needs Wi-Fi to work accurately, allowing you to use voice commands, control smart home devices, and access the internet for updates and information. In this article, weâll walk you through
5 min read
How to find available WiFi networks using Python?
WiFi (Wireless Fidelity) is a wireless technology that allows devices such as computers (laptops and desktops), mobile devices (smartphones and wearables), and other equipment (printers and video cameras) to interface with the Internet. We can find out the names of the WiFi names with the help of Py
2 min read
How to Make API Call Using Python
APIs (Application Programming Interfaces) are an essential part of modern software development, allowing different applications to communicate and share data. Python provides a popular library i.e. requests library that simplifies the process of calling API in Python. In this article, we will see ho
3 min read
How to control PC from anywhere using Python?
Prerequisite - Socket programming in Python In this solution, we use the concept of Socket Programming for establishing communication between two computers. Socket Programming in Python Socket Programming is a way of connecting two systems on a network to communicate with each other. Sockets are th
2 min read
How to Build a WiFi Scanner in Python using Scapy?
In this article, we are going to build a WiFi Scanner in Python using Scapy. WiFi Scanning or Network scanning refers to the scanning of the whole network to which we are connected and try to find out what are all the clients connected to our network. We can identify each client using their IP and M
3 min read