rockymeza / wifi

[unmaintained] WiFi tools for linux

Home Page:http://pypi.python.org/pypi/wifi

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Not comprehensive scan

jhadjar opened this issue · comments

TL;DR: I have a more comprehensive and exhaustive scan with iwlist wlan0 scan than using wifi.Cell.all('wlan0').

The point is: This is random. Sometimes, the module shows all available networks. Sometimes it only shows the one I'm connected to.

Background:

I have a router and a repeater. Both "broadcast" the same SSID, but obviously have different MAC addresses.

I need to change the Wifi password through the router interface (telnet). What this does is that the repeater can't access the router anymore, but still serves the SSID and has the strongest signal, so I need to connect to the router specifically.

When I do a iwlist wlan0 scan , I always have the results.

When I use the module, it depends. So I have to stop the Network Manager and start it again, wait 10 seconds and do a scan to get the networks' list.

Additional info for memo:

Router: SpeedTouch 585v6.
Repeater: Dlink DIR-505L.

Hi. Thanks for the bug report.

The only time I've experienced it only showing the network I'm connected to is when I'm not running as root. The iwlist program tries to limit the actual scanning when not root so as to conserve power. It can do one of two things.

  1. If there was a scan recently, print it from cache.
  2. If not, print the currently enabled network.

Are you running wifi as root?

When you say that you need to restart network manager, are you talking about Network Manager the program from gnome? I'm not sure if I mentioned this in the docs, but last time I checked wifi and network manager don't play nice together.

I'm importing the module (Python), but I'm executing the program as root. So yes, I run both iwlist and my program as root.

My way around this is this (ugly, I know, but it's temporary):

subprocess.call(["service", "network-manager", "stop"])
subprocess.call(["service", "network-manager", "start"])
sleep(10)
cells = wifi.Cell.all('wlan0')

It gets the "fresh" scan. And then from this, I get SSIDs and MACs. I match against my router's MAC to make a "scheme" to connect to it.

I'm making baby steps, but despite this, it's pretty cool. Thanks.

Can you try disabling network manager altogether before running the wifi
scan?

-rocky
2014年4月17日 上午12:52于 "Jugurtha Hadjar" notifications@github.com写道:

I'm importing the module (Python), but I'm executing the program as root.
So yes, I run both iwlist and my program as root.

My way around this is this (ugly, I know, but it's temporary):

subprocess.call(["service", "network-manager", "stop"])
subprocess.call(["service", "network-manager", "start"])
sleep(10)
cells = wifi.Cell.all('wlan0')

It gets the "fresh" scan. And then from this, I get SSIDs and MACs. I
match against my router's MAC to make a "scheme" to connect to it.

I'm making baby steps, but despite this, it's pretty cool. Thanks.


Reply to this email directly or view it on GitHubhttps://github.com//issues/37?utm_campaign=website&utm_source=sendgrid.com&utm_medium=email#issuecomment-40623380
.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/wifi/scan.py", line 31, in all
    raise InterfaceError(e.output.strip())
wifi.exceptions.InterfaceError: wlan0     Interface doesn't support scanning : Network is down

I get this using "sudo iwlist wlan0 scan" too. I think I've seen thise somewhere in issues.

Yeah, go ahead and try to connect to a network (it doesn't have to be
available currently) even if it doesn't connect, you will manage to get the
interface up. I really need to figure out how to get the interface up
without a network.

-rocky
2014年4月17日 上午1:03于 "Jugurtha Hadjar" notifications@github.com写道:

Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/wifi/scan.py", line 31, in all
raise InterfaceError(e.output.strip())
wifi.exceptions.InterfaceError: wlan0 Interface doesn't support scanning :
Network is down

I get this using "sudo iwlist wlan0 scan" too. I think I've seen thise
somewhere in issues.


Reply to this email directly or view it on GitHubhttps://github.com//issues/37#issuecomment-40624673
.

I get this

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/wifi/scheme.py", line 155, in activate
    subprocess.check_output(['/sbin/ifdown', self.interface], stderr=subprocess.STDOUT)
  File "/usr/lib/python2.7/subprocess.py", line 544, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['/sbin/ifdown', 'wlan0']' returned non-zero exit status 1

Here's my code:

subprocess.call(["service", "network-manager", "stop"])
subprocess.call(["service", "avahi-daemon", "stop"])
subprocess.call(["killall", "wpa_supplicant"])
subprocess.call(["service", "network-manager", "start"])

sleep(10)


cells = wifi.Cell.all('wlan0')

ssid = []
mac = []

for cell in cells:
    ssid.append(str(cell.ssid))
    mac.append(str(cell.address))

mac_ssid_map = dict(zip(mac, ssid)) 

print mac_ssid_map

cell = cells[0]
scheme = wifi.Scheme.for_cell('wlan0', our_ssid, cell, router_password)
scheme.save()
connection = scheme.activate()

Some stuff isn't necessary, but just toying with it (like the dict stuff to make a nice one).
Stopping the avahi-daemon and killing wpa_supplicant is due to the fact that sometimes, I have problems until I do that and start from a fresh setting.

commented

Hi,
I get also the same Bug:

Traceback (most recent call last):
  File "/home/.../workspace/client-wifi-configuration/wifimanage/linux/__init__.py", line 39, in <module>
    scheme.activate()
  File "/home/.../workspace/client-wifi-configuration/venv/local/lib/python2.7/site-packages/wifi/scheme.py", line 155, in activate
    subprocess.check_output(['/sbin/ifdown', self.interface], stderr=subprocess.STDOUT)
  File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['/sbin/ifdown', 'wlan0']' returned non-zero exit status 1

and the code:

    cell  =  Cell.all('wlan0')[ 0 ]
    scheme  =  Scheme.for_cell('wlan0','home', cell,'pw')
    scheme.save() #success save scheme in /etc/network/interfaces
    scheme.activate()

the scheme :

iface wlan0-home inet dhcp
    wpa-psk 2252012b5441f871ad6e27192d0a9d81797fded0be25525d9fb2c9e86333c772
    wpa-ssid ....
    wireless-channel auto

Looks like I'm facing the same issue, I wonder if there is a nice solution to this rather than the work around, I can't afford to stop my network service at any instant as I have a computer which has ssh'd and would keep constantly communicating. I have tried using iwlist as well and I did put my file in the sudoers file. But the iwlist command fails randomly when i call it through subprocess.check_output.

Am getting same bug:

Traceback (most recent call last):
  File "/home/.../workspace/client-wifi-configuration/wifimanage/linux/__init__.py", line 39, in <module>
    scheme.activate()
  File "/home/.../workspace/client-wifi-configuration/venv/local/lib/python2.7/site-packages/wifi/scheme.py", line 155, in activate
    subprocess.check_output(['/sbin/ifdown', self.interface], stderr=subprocess.STDOUT)
  File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['/sbin/ifdown', 'wlan0']' returned non-zero exit status 1

From what I was able to find from ifconfig command, my wi-fi network interface is wlp2s0 as to wlan0... Please ther should be a way of auto-detecting the network interface and also in this code:
scheme = Scheme.for_cell('wlan0', 'home', cell, passkey)
what is the 'home' argument doing and what type(str, int, bool....) is passed into cell and passkey?

@rikoz
Could you please try:

pip install wifi==0.8.0rc1

Line 155 referenced doesn't contain that code and I've looked at the current scheme.py and there are no more hardcoded references to wlan0.

is everything working on version 0.8.0rc1??, perhaps i would like us to have a video chat on this

Hi everyone, I have your same problem, did you fix with pip install wifi==0.8.0rc1 or did you find other way?

yes, a bit fixed and had another way of auto-detect my wifi interface

Ok because for me didn't work, I will try to find a way and share it here if I success.

screenshot from 2018-05-02 17-12-58
first detect interface name
.....
then use here: `

-- coding: utf-8 --

import wifi
from sik_wireless import sik_iface

iface_name = sik_iface()

def Search():
wifilist = []

cells = wifi.Cell.all(iface_name)

for cell in cells:
    wifilist.append(cell)

return wifilist

def FindFromSearchList(ssid):
wifilist = Search()

for cell in wifilist:
    if cell.ssid == ssid:
        return cell

return False

def FindFromSavedList(ssid):
cell = wifi.Scheme.find(iface_name, ssid)

if cell:
    return cell

return False

def Connect(ssid, password=None):
cell = FindFromSearchList(ssid)

if cell:
    savedcell = FindFromSavedList(cell.ssid)

    # Already Saved from Setting
    if savedcell:
        savedcell.activate()
        return cell

    # First time to conenct
    else:
        if cell.encrypted:
            if password:
                scheme = Add(cell, password)

                try:
                    scheme.activate()

                # Wrong Password
                except wifi.exceptions.ConnectionError:
                    Delete(ssid)
                    return False

                return cell
            else:
                return False
        else:
            scheme = Add(cell)

            try:
                scheme.activate()
            except wifi.exceptions.ConnectionError:
                Delete(ssid)
                return False

            return cell

return False

def Add(ssid, password=None):
cell = FindFromSearchList(ssid)

if not cell:
	return False

scheme = wifi.Scheme.for_cell(iface_name, ssid, cell, password)
scheme.save()
return scheme

def Delete(ssid):
if not ssid:
return False

cell = FindFromSavedList(ssid)

if cell:
    cell.delete()
    return True

return False

if name == 'main':
# Search wifi and return wifi list
print Search()

# Connect wifi with password & without password
print Connect('Openwifi')
print FindFromSearchList('koz..py')
print Add('#koz iPhone', 'omocc5n4jr7zn')
print FindFromSavedList('#koz iPhone')
print Connect('#koz iPhone', 'omocc5n4jr7zn')

# Delete wifi from auto connect list
#print Delete('Deletewifi')`

rikoz for what I understood I cannot use the Scheme.activate() because it produce the error reported in this conversation and also searching online I saw that it's something related with that shell command sudo ifup wlan0 that respond me with this messagge ifup: unknown interface wlan0.

I found the solution for my problem that is not related to the real question (scan network), but I want to share it.
In my case I'm not working with libraries but directly with the shell, here I'm passing the SSID and PSW to the wifi_connect(ssid, psk) that it return the ip address of my device.

SO: rasbian stretch

import os
import time
import subprocess

wpa_supplicant_conf = "/etc/wpa_supplicant/wpa_supplicant.conf"
sudo_mode = "sudo "

def wifi_connect(ssid, psk):
    cmd_result = ""

    # write wifi config to file
    f = open('wifi.conf', 'w')
    f.write('ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n')
    f.write('update_config=1\n')
    f.write('country=US\n')
    f.write('\n')
    f.write('network={\n')
    f.write('    ssid="' + ssid + '"\n')
    f.write('    psk="' + psk + '"\n')
    f.write('    key_mgmt=WPA-PSK\n')
    f.write('}\n')
    f.close()
    time.sleep(1)

    # move to the specific folder and overwrite the old file
    cmd = 'sudo mv wifi.conf ' + wpa_supplicant_conf
    cmd_result = os.system(cmd)
    print(cmd + " - " + str(cmd_result))
    time.sleep(1)

    # reconfigure the wifi service
    cmd = 'wpa_cli -i wlan0 reconfigure'
    cmd_result = os.system(cmd)
    print(cmd + " - " + str(cmd_result))
    time.sleep(10)

    # keep all the information about the network
    p = subprocess.Popen(['ifconfig', 'wlan0'], stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)

    out, err = p.communicate()
    ip_address = "<Not Set>"

    # extract the IP address
    for l in out.split(b'\n'):
        if l.strip().startswith(b'inet '):
            ip_address = l.strip().split(b'inet ')[1].split(b' ')[0]

    return ip_address


ip = wifi_connect('SSID', 'PSW')

if ip == "<Not Set>":
    print('Fail to connect to Internet')
else:
    print('Connection established: IP address: ' + ip.decode("utf-8"))