connect wifi with python or linux terminal [closed]

别来无恙 提交于 2019-11-28 11:45:42

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!