2013-12-09 12 views
5

Voglio utilizzare un dongle WiFi con RaspberryPi, (è come una CPU senza WiFi integrato). Ho bisogno di scrivere uno script python che scansiona automaticamente le reti WiFi e che sia necessario stabilire automaticamente una connessione con SSID e password conosciuti.script python per RaspberryPi per connettere automaticamente il wifi

Ciò significa che è necessario fornire la password per la rete WiFi da un file e la cosa rimanente è eseguire la scansione e la connessione automaticamente.

Ho letto un file dal Web che contiene nome e password SSID WiFi.

Ho bisogno di scrivere uno script che scansiona ed elenca i netword correnti e lo abbina al SSID dal file e crea automaticamente la connessione a questa rete conosciuta.

Raspberry Pi OS: Rasbian

+0

La tua domanda non lo fa sembra avere senso in qualche modo. Vuoi ottenere i dettagli del wifi dal web e poi usarli per connettersi al wifi? Come si fa a farlo senza una connessione Internet? –

+0

Non sono sicuro di cosa hai bisogno di aiuto, stai cercando uno script di Raspberry che possa connettersi automaticamente a una rete se si scopre dalla scansione dell'attuale ambiente WiFi? E vuoi scrivere la sceneggiatura o vuoi trovare un modulo che faccia questo per te? – qrikko

risposta

17

wifi è una libreria Python per la scansione e la connessione a reti WiFi su linux. Puoi usarlo per scansionare e connetterti a reti wireless.

Non ha alcun supporto integrato per la connessione automatica a una rete, ma è possibile scrivere facilmente uno script per farlo. Ecco un esempio di un'idea di base su come farlo.

#!/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 

Ho appena scritto e sembra funzionare. Solo per quello che sai, ho scritto la libreria wifi. Se vuoi che aggiunga questa funzione a quella libreria, potrei.

+2

Ehi @rockymeza, penso che una funzione di autoconnect potrebbe essere fantastica e sarebbe molto utile per gli utenti di raspberry pi in particolare! – dalanmiller

+0

@rockymeza Non capisco come si usa? Non ho bisogno di generare una password? perché quando uso il tuo codice il mio wifi continua a non connettersi. Grazie –

+0

Avete qualcosa nell'output di 'scheme = list (Scheme.all())'? In caso contrario, è perché prima devi creare schemi. Per ulteriori informazioni, consultare http://wifi.readthedocs.org/en/latest/scanning.html#connecting-to-a-etwork. – rockymeza

1

Questa è una patch di scimmia della risposta di rockymeza sopra, in modo che Scheme utilizzi il file /etc/wpa_supplicant/wpa_supplicant.conf invece del file/etc/network/interfaces. Non riuscivo a far funzionare la sua classe Scheme sui miei pi3 in quanto sembra che Schemes aggiunga iface wlan0-SSIDname per ogni rete al file/etc/network/interfaces, e non ci sia alcuna mappatura o nulla che gli dica che ifup wlan0-SSIDname è associato a '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 

Per creare lo schema, basta fare questo:

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

vostro/etc// file di interfacce di rete dovrebbe assomigliare a questa, o simili:

# 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 
Problemi correlati