connect wifi with python or linux terminal

17,222

Solution 1

Here is a general approach using python os module and Linux iwlist command for searching through the list of wifi devices and nmcli command in order to connect to a the intended device.

In this code the run function finds the SSID of devices that match with your specified name (which can be a regex pattern or a unique part of the server name) then connects to all the devices that match with your expected criteria, by calling the connection function.

"""
Search for a specific wifi ssid and connect to it.
written by kasramvd.
"""
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):
        try:
            os.system("nmcli d wifi connect {} password {} iface {}".format(name,
       self.password,
       self.interface_name))
        except:
            raise
        else:
            return True

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()

Solution 2

At first try to look at these links: http://packages.ubuntu.com/raring/python-wicd https://wifi.readthedocs.org/en/latest/

And if you want to use bash commands via python try this code:

from subprocess import Popen, STDOUT, PIPE
from time import sleep

handle = Popen('netsh wlan connect wifi_name', stdout=PIPE, stdin=PIPE, shell=True,  stderr=STDOUT)

sleep(10)

handle.stdin.write(b'wifi_password\n')
while handle.poll() == None:
    print handle.stdout.readline().strip()  # print the result

But make sure you are running as a super user in Linux but there is no problem in Windows.

Share:
17,222

Related videos on Youtube

I.el-sayed
Author by

I.el-sayed

Updated on June 04, 2022

Comments

  • I.el-sayed
    I.el-sayed almost 2 years

    I am trying to connect to wifi through python and linux terminal but in both cases it is not working with me.

    For python, I am using this library https://wifi.readthedocs.org/en/latest/scanning.html scanning and saving the scheme is working fine but whenever I type this line of code scheme.activate() and I get no output

    Any ideas what is wrong with the library and if you have used it before or not??

    I tried also to connect to WiFi networks using the CLI. I Googled and found that I should do these three statements 1- iwlist wlan0 scan // to scan the wireess networks 2- iwconfig wlan0 essid "Mywirelessnetwork" // to associate with the network 3- dhclient wla0 // To get an UP

    Whenever I do step 2 and then check iwconfig wlan0 I found that the wireless interface is not associated !!

    Any ideas ???

    What I am trying to do is to have a library of a way to connect to the wifi preferably through a python function or a library and tested on raspberry PI because I am building some applications that require network connection.

  • I.el-sayed
    I.el-sayed over 10 years
    the wicd library looks promising but I can't find any documentation of how I can use it with python. Do you have any good tutorial or any kind of documentation !! ?? PS: I Googled :)
  • hamidfzm
    hamidfzm over 10 years
    You can take a look at wicd home page at < wicd.sourceforge.net > and in there you can find any thing about it or simple use help('wicd') in your python shell!
  • I.el-sayed
    I.el-sayed over 10 years
    I checked help('wicd') nothing except the contents of the module and the <wicd.sourceforge.net/moinmoin> is down which is the wiki of wicd
  • hamidfzm
    hamidfzm over 10 years
    There is no problem in there. Where is your country? Try using VPN to view. I'm looking at it right now.
  • I.el-sayed
    I.el-sayed over 10 years
    I am from Egypt ... I don't think it is a VPN problem ... this is what I got <tinypic.com/r/6zyctz/8> looks like their wiki is not working
  • hamidfzm
    hamidfzm over 10 years
    You should absolutely use some VPN. It's the wiki page I see: i58.tinypic.com/wul475.png
  • I.el-sayed
    I.el-sayed over 10 years
    dude the wicd homepage is working but if you click on the top right exactly no "wiki" you will get the error page .... you can visit this link too <wicd.sourceforge.net/moinmoin>
  • hamidfzm
    hamidfzm over 10 years
    Ok, try to take look at last link in the answer.
  • Rishabh Agrahari
    Rishabh Agrahari almost 7 years
    If server_name has spaces in the name, then your os.system in connection function will take it as different parameters..so this is a bug in you code.