Skip to content

Instantly share code, notes, and snippets.

@CyanGirl
Created July 31, 2021 15:34
Show Gist options
  • Save CyanGirl/ce608370762cc20e2ec77239e61d051b to your computer and use it in GitHub Desktop.
Save CyanGirl/ce608370762cc20e2ec77239e61d051b to your computer and use it in GitHub Desktop.
The program can be used to find the 3 strongest WiFis available in your network and upon choosing, connects to it with password in Python 3 , on Windows.
import subprocess
import getpass
import os
import time
import pywifi
from pywifi import PyWiFi
from pywifi import const
from pywifi import Profile
class ConnectWifi:
# method to connect to the wifi with password
def connect_wifi(self, ssid, password):
wifi = PyWiFi()
ifaces = wifi.interfaces()[0]
ifaces.scan()
wifi = pywifi.PyWiFi()
iface = wifi.interfaces()[0]
profile = 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 = password
iface.remove_all_network_profiles()
tmp_profile = iface.add_network_profile(profile)
print("\tConnecting to WiFi....")
time.sleep(2)
iface.connect(tmp_profile)
time.sleep(2)
if ifaces.status() == const.IFACE_CONNECTED:
print("Connected to the WiFi successfully!")
else:
print("Failed to connect to the WiFi!")
# method to get the 3 strongest WiFis available in the network
def get_available_wifi(self):
cmd = ['netsh', 'wlan', 'show', 'network', 'mode=Bssid']
output = subprocess.check_output(cmd).decode('ascii').replace("\r", "")
tempnames = output.split("\n\n")
nets = []
for i in range(1, len(tempnames)-1):
temp = tempnames[i].split("\n")
ssid = temp[0].rstrip().split(" : ")[-1]
signal = int(temp[5].rstrip().split(" : ")[-1][:-1])
nets.append((ssid, signal))
nets = sorted(nets, reverse=True, key=lambda x: x[1])[:3]
return(nets)
# driver method
def execute(self):
networks = self.get_available_wifi()
print("Your available networks are :")
for key, network in enumerate(networks):
print(f"\t>> [{key+1}] {network[0]}")
choice = input("Your Choice : |\n\t>> ")
if choice not in "123":
print("Wrong Choice Entered.")
return False
password = getpass.getpass()
ssid = networks[int(choice)-1][0]
print(f"You selected WiFi: {ssid}")
self.connect_wifi(ssid, password)
if __name__ == "__main__":
obj = ConnectWifi()
obj.execute()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment