用于RaspberryPi的python脚本自动连接wifi

时间:2013-12-09 12:24:54

标签: python wifi raspberry-pi

我想用RaspberryPi操作WiFi加密狗(它就像没有内置WiFi的CPU)。我需要编写一个自动扫描WiFi网络的python脚本,并且需要使用已知的SSID和密码自动建立连接。

这意味着我需要从文件中提供WiFi网络的密码 剩下的就是自动扫描和连接。

我从网上读取了一个包含WiFi SSID名称和密码的文件。

我需要编写一个脚本,扫描并列出当前的网络字,并将其与文件中的SSID相匹配,并进一步自动创建与此已知网络的连接。

RaspberryPi操作系统:Rasbian

3 个答案:

答案 0 :(得分:17)

wifi是一个python库,用于扫描和连接到linux上的wifi网络。您可以使用它来扫描和连接到无线网络。

它没有任何内置支持自动连接到网络,但您可以轻松编写脚本来执行此操作。以下是如何执行此操作的基本概念示例。

#!/usr/bin/python
from __future__ import print_function

from wifi import Cell, Scheme

# get all cells from the air
ssids = [cell.ssid for cell in Cell.all('wlan0')]

schemes = list(Scheme.all())

for scheme in schemes:
    ssid = scheme.options.get('wpa-ssid', scheme.options.get('wireless-essid'))
    if ssid in ssids:
        print('Connecting to %s' % ssid)
        scheme.activate()
        break

我刚刚写了它,它似乎工作。就这么你知道,我写了wifi库。如果您希望我将此功能添加到该库,我可以。

答案 1 :(得分:1)

这是上面的rockmeza的一个补丁,因此该方案将使用/etc/wpa_supplicant/wpa_supplicant.conf文件而不是/ etc / network / interfaces文件。我无法让他的Scheme类处理我的pi3s,因为似乎Schemes只是将每个网络的iface wlan0-SSIDname添加到/ etc / network / interfaces文件中,并且没有映射或任何东西可以告诉它ifup wlan0-SSIDname与' wlan0'。

相关联
import re
from wifi import Cell, Scheme
import wifi.subprocess_compat as subprocess
from wifi.utils import ensure_file_exists

class SchemeWPA(Scheme):

    interfaces = "/etc/wpa_supplicant/wpa_supplicant.conf"

    def __init__(self, interface, name, options=None):
        self.interface = interface
        self.name = name
        self.options = options or {} 

    def __str__(self):
        """
        Returns the representation of a scheme that you would need
        in the /etc/wpa_supplicant/wpa_supplicant.conf file.
        """

        options = ''.join("\n    {k}=\"{v}\"".format(k=k, v=v) for k, v in self.options.items())
        return "network={" + options + '\n}\n'

    def __repr__(self):
            return 'Scheme(interface={interface!r}, name={name!r}, options={options!r}'.format(**vars(self))
    def save(self):
        """
        Writes the configuration to the :attr:`interfaces` file.
        """
        if not self.find(self.interface, self.name):
            with open(self.interfaces, 'a') as f:
                f.write('\n')
                f.write(str(self))        

    @classmethod
    def all(cls):
        """
        Returns an generator of saved schemes.
        """
        ensure_file_exists(cls.interfaces)
        with open(cls.interfaces, 'r') as f:
            return extract_schemes(f.read(), scheme_class=cls) 
    def activate(self):
        """
        Connects to the network as configured in this scheme.
        """

        subprocess.check_output(['/sbin/ifdown', self.interface], stderr=subprocess.STDOUT)
        ifup_output = subprocess.check_output(['/sbin/ifup', self.interface] , stderr=subprocess.STDOUT)
        ifup_output = ifup_output.decode('utf-8')

        return self.parse_ifup_output(ifup_output)
    def delete(self):
        """
        Deletes the configuration from the /etc/wpa_supplicant/wpa_supplicant.conf file.
        """
        content = ''
        with open(self.interfaces, 'r') as f:
            lines=f.read().splitlines()
            while lines:
                line=lines.pop(0)

                if line.startswith('#') or not line:
                    content+=line+"\n"
                    continue

                match = scheme_re.match(line)
                if match:
                    options = {}
                    ssid=None
                    content2=line+"\n"
                    while lines and lines[0].startswith(' '):
                        line=lines.pop(0)
                        content2+=line+"\n"
                        key, value = re.sub(r'\s{2,}', ' ', line.strip()).split('=', 1)
                        #remove any surrounding quotes on value
                        if value.startswith('"') and value.endswith('"'):
                            value = value[1:-1]
                        #store key, value
                        options[key] = value
                        #check for ssid (scheme name)
                        if key=="ssid":
                            ssid=value
                    #get closing brace        
                    line=lines.pop(0)
                    content2+=line+"\n"

                    #exit if the ssid was not found so just add to content
                    if not ssid:
                        content+=content2
                        continue
                    #if this isn't the ssid then just add to content
                    if ssid!=self.name:
                        content+=content2

                else:
                    #no match so add content
                    content+=line+"\n"
                    continue

        #Write the new content
        with open(self.interfaces, 'w') as f:
            f.write(content)    

scheme_re = re.compile(r'network={\s?')


#override extract schemes
def extract_schemes(interfaces, scheme_class=SchemeWPA):
    lines = interfaces.splitlines()
    while lines:
        line = lines.pop(0)
        if line.startswith('#') or not line:
            continue

        match = scheme_re.match(line)
        if match:
            options = {}
            interface="wlan0"
            ssid=None

            while lines and lines[0].startswith(' '):
                key, value = re.sub(r'\s{2,}', ' ', lines.pop(0).strip()).split('=', 1)
                #remove any surrounding quotes on value
                if value.startswith('"') and value.endswith('"'):
                    value = value[1:-1]
                #store key, value
                options[key] = value
                #check for ssid (scheme name)
                if key=="ssid":
                    ssid=value

            #exit if the ssid was not found
            if ssid is None:
                continue
            #create a new class with this info
            scheme = scheme_class(interface, ssid, options)

            yield scheme

要创建方案,只需执行以下操作:

scheme=SchemeWPA('wlan0',cell.ssid,{"ssid":cell.ssid,"psk":"yourpassword"})

你的/ etc / network / interfaces文件应该是这样的,或类似的:

# interfaces(5) file used by ifup(8) and ifdown(8)

# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'
# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

iface default inet dhcp

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

答案 2 :(得分:0)

谢谢大家的回答,我提出了如下简单的解决方案

def wifiscan():

   allSSID = Cell.all('wlan0')
   print allSSID # prints all available WIFI SSIDs
   myssid= 'Cell(ssid=vivekHome)' # vivekHome is my wifi name

   for i in range(len(allSSID )):
        if str(allSSID [i]) == myssid:
                a = i
                myssidA = allSSID [a]
                print b
                break
        else:
                print "getout"

   # Creating Scheme with my SSID.
   myssid= Scheme.for_cell('wlan0', 'home', myssidA, 'vivek1234') # vive1234 is the password to my wifi myssidA is the wifi name 

   print myssid
   myssid.save()
   myssid.activate()

wifiscan()