Skip to content

Commit fbf7572

Browse files
author
Subhasree Bose
committed
added connect_strongest_wifi
1 parent 0f1bc1d commit fbf7572

File tree

3 files changed

+139
-0
lines changed

3 files changed

+139
-0
lines changed

connect_strongest_wifi/README.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Connect to the Strongest Wi-Fi
2+
3+
## About
4+
5+
The Script can be used to find 3 strongest Wi-Fi's available based on signal strength in Windows OS.
6+
7+
User can then choose one of the networks from the list of 3 Wi-Fi detected and give the password for the same. Once password is provided, the script connects to the Wi-Fi specified.
8+
9+
- Language: Python 3
10+
- Package used: pywifi
11+
- OS: Windows
12+
13+
## Pre-requisites
14+
15+
To execute the script, the following are required:
16+
17+
1. Python 3
18+
2. pip
19+
20+
## Setup instructions
21+
22+
1. Navigate to the directory:
23+
24+
```
25+
cd connect_strongest_wifi
26+
```
27+
28+
2. Install the requirements:
29+
30+
```
31+
pip install -r requirements.txt
32+
```
33+
34+
## Detailed Explanation of Script
35+
36+
When the script is executed, the main function is being invoked which in turns invoke the get_available_wifi(). This function scan through the available Wi-Fi and returns the entire list of it with SSID and their respective signal, in Windows.
37+
38+
In main, slicing till top 3 SSIDs have been done to take the 3 strongest Wi-Fi signals available. Then, the options are displayed for the User to choose from one of them. Once the User chooses a connection, input for password is prompted.
39+
40+
Next, the chosen SSID and the provided password is passed to the connect_wifi() and connection is established with the Wi-Fi.
41+
42+
Note: If the script fails to connect with Wi-Fi even with correct password, try increasing the Sleep time in connect_wifi().
43+
44+
## Execution
45+
46+
Run the script directly with :
47+
48+
```
49+
python connect_strongest_wifi.py
50+
```
51+
52+
When prompted for which Wi-Fi to choose, enter the Option Number with respect to the Wi-Fi name. Enter the password for the same to get connected.
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import subprocess
2+
import getpass
3+
import time
4+
from pywifi import PyWiFi
5+
from pywifi import const
6+
from pywifi import Profile
7+
8+
9+
def connect_wifi(ssid, password):
10+
# function to connect to Wi-Fi with Password
11+
12+
wifi = PyWiFi()
13+
iface = wifi.interfaces()[0]
14+
iface.disconnect() # disconnects from the current Wi-Fi if any
15+
time.sleep(2)
16+
17+
profile = Profile() # adding new Profile for given Wi-Fi
18+
profile.ssid = ssid
19+
profile.auth = const.AUTH_ALG_OPEN
20+
profile.akm.append(const.AKM_TYPE_WPA2PSK)
21+
profile.cipher = const.CIPHER_TYPE_CCMP
22+
profile.key = password
23+
24+
print("\nConnecting to WiFi....")
25+
iface.connect(iface.add_network_profile(profile))
26+
time.sleep(5)
27+
28+
if iface.status() == const.IFACE_CONNECTED:
29+
print("\t>> Connected Successfully!")
30+
else:
31+
print("\t>> Failed to Connect!")
32+
33+
34+
def get_available_wifi():
35+
# function to get 3 strongest Wi-Fi with SSIDs in Windows
36+
37+
try:
38+
39+
cmd = ['netsh', 'wlan', 'show', 'network', 'mode=Bssid']
40+
wifidata = subprocess.check_output(cmd).decode(
41+
'ascii').replace("\r", "").split("\n\n")
42+
43+
except subprocess.CalledProcessError:
44+
print("\nWhoops! Your Wi-Fi seems to be powered off.")
45+
raise SystemExit
46+
47+
else:
48+
networks = []
49+
for i in range(1, len(wifidata)-1): # parsing SSIDs and signals
50+
temp = wifidata[i].split("\n")
51+
ssid = temp[0].rstrip().split(" : ")[-1]
52+
signal = int(temp[5].rstrip().split(" : ")[-1][:-1])
53+
networks.append((ssid, signal))
54+
55+
networks = sorted(networks, reverse=True, key=lambda x: x[1])
56+
return (networks)
57+
58+
59+
def main():
60+
# main function to take 3 strongest Wi-Fis and connect
61+
62+
networks = get_available_wifi()[:3] # get top 3 strongest networks
63+
64+
print(f"\nYour {len(networks)} Strongest Networks are :")
65+
for key, network in enumerate(networks):
66+
print(f"\t[{key+1}] {network[0]}, Signal: {network[1]}%")
67+
68+
choice = input("\nPlease enter your choice : \n\t>> ").strip()
69+
if not(choice.isdigit() and 1 <= int(choice) <= len(networks)):
70+
print("Wrong Choice Entered. Exiting...")
71+
return False
72+
73+
ssid = networks[int(choice)-1][0]
74+
75+
# check if the chosen SSID is already connected
76+
if ssid in subprocess.check_output("netsh wlan show interfaces").decode():
77+
print(f"\nYou are already connected to {ssid} Network. \nExiting...")
78+
else:
79+
print(f"\nYou Selected: {ssid}")
80+
password = getpass.getpass()
81+
# connect to the chosen SSID with password
82+
connect_wifi(ssid, password)
83+
84+
85+
if __name__ == "__main__":
86+
main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pywifi==1.1.12

0 commit comments

Comments
 (0)