2013-12-09 8 views
5

RaspberryPiでWiFiドングルを操作したいです(内蔵WiFiなしのCPUのようなものです)。私はWiFiネットワークを自動的にスキャンし、既知のSSIDとパスワードで接続を自動的に確立する必要があるpythonスクリプトを書く必要があります。RaspberryPiが自動的にWi-Fiに接続するためのPythonスクリプト

これは、ファイルからWiFiネットワークのパスワードを提供する必要があることを意味し、残りのものはスキャンを実行して自動的に接続することです。

私はWiFi SSID名とパスワードを含むファイルをWebから読みました。

現在のネットワークをスキャンしてリストし、それをファイルのSSIDに一致させ、さらにこの既知のネットワークへの接続を自動的に作成するスクリプトを作成する必要があります。

RaspberryPi OS:Rasbian

+0

ご質問はしません何とかやっているようだ。あなたはウェブからの無線LANの詳細を取得し、それらを使用して無線LANに接続したいですか?インターネット接続なしでどうやってやろうとしていますか? –

+0

私はあなたが助けを必要としているかどうか分かりません。ネットワークに接続できるラズベリーのスクリプトを探していますか?そしてあなたはスクリプトを書くか、これを行うモジュールを探したいのですか? – qrikko

答えて

17

wifiは、スキャンおよびLinuxでのWi-Fiネットワークに接続するためのPythonライブラリです。ワイヤレスネットワークをスキャンして接続することができます。

ネットワークに自動的に接続するためのサポートは組み込まれていませんが、そのためのスクリプトを簡単に作成できます。これを行う方法の基本的な考え方の例を次に示します。

#!/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ライブラリを書いた。この機能をそのライブラリに追加したい場合は、できます。

+2

こんにちは@rockymeza、私はオートコネクション機能が素晴らしいと思う、特にラズベリーパイユーザーにとって非常に役立つと思います! – dalanmiller

+0

@rockymeza私はそれを使用する方法を理解していない?パスワードを生成する必要はありませんか?私があなたのコードを使用するとき、私のWiFiはまだ接続していなかったからです。ありがとうございます –

+0

'schemes = list(Scheme.all())'の出力に何かがありますか?そうでない場合は、まずスキームを作成する必要があるからです。詳細については、http://wifi.readthedocs.org/en/latest/scanning.html#connecting-to-a-networkをご覧ください。 – rockymeza

1

これは上記のrockymezaさんの答えのサルパッチです。そのため、/ etc/network/interfacesファイルの代わりに/etc/wpa_supplicant/wpa_supplicant.confファイルが使用されます。 Schemeが各ネットワークのiface wlan0-SSIDnameを/ etc/network/interfacesファイルに追加するだけで、自分のpi3で自分のSchemeクラスを動作させることはできませんでした。 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 
関連する問題