Python连接Ubuntu 环境 wifi流程

 

1、获取网络接口列表

通过wifi_net.py 的query_net_cards方法获取终端物理网络接口列表及IP信息:
获取物理网络接口列表:

ls -d /sys/class/net/*/device | cut -d/ -f5
或者:
find /sys/class/net -type l -not -lname '*virtual*' -printf '%f\n'
iwifconfig

代码示例:

# 查询所有物理网卡
def _query_net_card_info(if_name):
net_card_info = {
"mac": "",
"type": "eth",
"ip": "",
"netmask": "",
}
try:
net_info = netifaces.ifaddresses(if_name)
except ValueError:
logger.error("No such interface: %s" % if_name)
return net_card_info
# 如果为无线网卡,将修改网卡类型为wlan
if if_name in common.cmd_excute("iw dev | awk '$1==\"Interface\" {print $2}'"):
net_card_info["type"] = "wlan" net_card_info["mac"] = net_info[netifaces.AF_LINK][0]["addr"].upper()
ipv4_info = net_info.get(netifaces.AF_INET)
if ipv4_info:
net_card_info["ip"] = ipv4_info[0]["addr"]
net_card_info["netmask"] = ipv4_info[0]["netmask"]
return net_card_info @staticmethod
def query_net_cards():
"""
{
"enp2s0": // 接口名称
{
"mac": "98:FA:9B:99:E5:6A", // MAC地址
"type": "eth", // 接口类型,eth-有线网卡, wlan-无线网卡
"ip": "192.168.2.90", // 接口当前IP
"netmask": "255.255.255.0", // 接口掩码
"dns":"192.168.2.1", // dns服务器ip
"gateway": "192.168.2.1" // 网管地址
},
"wlan0":
{
"mac": "98:FA:9B:99:E5:6A", // MAC地址
"type": "wlan", // 接口类型,eth-有线网卡, wlan-无线网卡
"ip": "", // 接口当前IP
"netmask": "", // 接口掩码
"dns":"192.168.2.1", // dns服务器ip
"gateway": "192.168.2.1" // 网管地址
}
}
"""
net_cards = dict()
# 获取所有物理网卡名称
command = "ls -d /sys/class/net/*/device | cut -d/ -f5"
interfaces = common.cmd_excute(command) # 获取dns服务器ip
dns_path = '/etc/resolv.conf'
dns_list = []
if os.path.exists(dns_path):
dns_list = common.cmd_excute("cat %s|grep ^nameserver|awk '{print $2}'" % dns_path, b_print=False)
# 获取网管地址
gateways = netifaces.gateways().get('default').get(netifaces.AF_INET) for interface in interfaces:
net_card = Network._query_net_card_info(if_name=interface)
net_card["dns"] = dns_list if dns_list else ""
net_card["gateway"] = gateways[0] if gateways else ""
net_cards[interface] = net_card
return net_cards

2、获取无线网络列表
通过wifi_net.py 的query_wifi_ssids方法获取扫描到的无线网络列表:

扫描无线网络:
通过iwlist 命令获取,需要解析命令行输出:

iwlist wlan0 scan

或,通过python库 wifi解析:

        def query_wifi_ssids(wifi_if):
import wifi
import codecs
ssid_list = []
try:
common.cmd_excute("ifconfig %s up" % wifi_if)
cell_list = wifi.Cell.all(wifi_if)
except wifi.exceptions.InterfaceError as e:
# 可能非Wifi接口
logger.error("_get_wireless_ssid_list exception: %s" % traceback.format_exc())
return ssid_list for cell in cell_list:
ssid_list.append(
{
"ssid": codecs.utf_8_decode(cell.ssid)[0].encode('utf-8'),
"mac": cell.address,
"encrypted": cell.encrypted,
"quality": cell.quality,
# "signal": cell.signal,
}
) return ssid_list

返回数据示例:

[
{
"ssid": "leifeng_2", // 无线网络SSID
"mac": "58:D9:D5:D3:FB:01", // 无线接入点MAC
"enctypted": True, // 是否加密
"quality": cell.quality //信号强度
},
{
"ssid": "leifeng_2_5G",
"mac": "58:D9:D5:D3:FB:05",
"enctypted": True,
"quality": cell.quality
}
]

3、连接无线网络,检查连接结果
connect_wifi方法连接无线网络:

# 配置无线网络:
wpa_passphrase "leifeng_2" "radeon123" > /etc/wpa_supplicant/wpa_supplicant.conf
# leifeng_2网络名称 radeon123 wifi密码
# 连接无线网络:
wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf &
# -B后台执行
    # 代码示例
def connect_wifi(net_card, ssid, password, static_ip=""):
"""连接wifi"""
wifi_conf_command = 'wpa_passphrase "%s" "%s" > /etc/wpa_supplicant/wpa_supplicant.conf' % (ssid, password)
common.cmd_excute(wifi_conf_command) wifi_conn_command = 'wpa_supplicant -i %s -c /etc/wpa_supplicant/wpa_supplicant.conf -B > /tmp/wifi_conn.txt' % net_card
logger.debug("Start wifi connection: %s " % wifi_conn_command)
common.cmd_excute(wifi_conn_command)
if not static_ip:
# flush
flush_command = "ip addr flush dev %s" % net_card
common.cmd_excute(flush_command)
# 自动分配ip地址
auto_command = "dhclient %s" % net_card
common.cmd_excute(auto_command)
else:
# 配置静态ip
manual_common = "ifconfig %s %s" %(net_card,static_ip)
common.cmd_excute(manual_common)
for i in range(10):
wifi_status_command = "cat /sys/class/net/{}/operstate".format(net_card)
wifi_status_process = subprocess.Popen(wifi_status_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
if wifi_status_process.stdout.readline() == "up":
logger.debug("wifi %s connection success") % ssid
break
time.sleep(1)
else:
wifi_result_command = "cat /tmp/wifi_conn.txt | grep reason=WRONG_KEY"
wifi_result_process = subprocess.Popen(wifi_result_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
shell=True)
if wifi_result_process.stdout.readline():
logger.debug("wifi %s connection fail,password error") % ssid
return False,"password error"
logger.debug("wifi %s connection timeout") % ssid
return False,"connect timeout"
return True,"success"

4、封装cmd命令

定义common.py文件,

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/11/11 下午3:21
import subprocess def shell_excute(rsyncStr, shell=False, b_print=True):
p = subprocess.Popen(rsyncStr, shell=shell,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = "".join(p.communicate())
return output def cmd_excute(command, b_trip=True, b_print=True):
ret_list = []
cmd_ret = shell_excute(command, shell=True, b_print=b_print).splitlines()
if b_trip:
for sline in cmd_ret:
if len(sline.strip()) != 0:
ret_list.append(sline.strip())
else:
ret_list = cmd_ret
return ret_list

  

python操作 linux连接wifi,查看wifi连接状态方法的更多相关文章

  1. python操作mongodb根据_id查询数据的实现方法

    python操作mongodb根据_id查询数据的实现方法   python操作mongodb根据_id查询数据的实现方法,实例分析了Python根据pymongo不同版本操作ObjectId的技巧, ...

  2. linux中可以查看端口占用的方法

    在自己搭建的服务器中,经常容易出现端口被占用的问题,那么怎么知道自己的端口是否被占用了呢? 可以使用下面的方法: linux中可以查看端口占用的方法. netstat -ant | grep 80 ( ...

  3. 在Linux终端中查看公有IP的方法详解

    首先回顾一下一般的查看IP的命令: ifconfigLinux查看IP地址的命令--ifconfigifconfig命令用于查看和更改网络接口的地址和参数 $ifconfig -a  lo0: fla ...

  4. python操作文件和目录查看、创建、删除、复制

    python内置了os模块可以直接调用操作系统提供的接口函数,os.name查询的是操作系统,‘nt’表示windows系统 >>> import os >>> o ...

  5. linux设置和查看环境变量的方法

    1.    显示环境变量HOME $ echo $HOME /home/redbooks 2.    设置一个新的环境变量hello $ export HELLO="Hello!" ...

  6. Linux设置和查看环境变量的方法 详解

    1. 显示环境变量HOME $ echo $HOME /home/redbooks 2. 设置一个新的环境变量hello $ export HELLO="Hello!" $ ech ...

  7. python 下载.whl 文件,查看已安装软件包方法

    下载地址       https://www.lfd.uci.edu/~gohlke/pythonlibs/ 另一个Python packages地址为    https://pypi.org/ 下载 ...

  8. 【转】Linux设置和查看环境变量的方法

    转: http://www.jb51.net/LINUXjishu/77524.html 1. 显示环境变量HOME $ echo $HOME /home/redbooks 2. 设置一个新的环境变量 ...

  9. python在linux中输出带颜色的文字的方法

    在开发项目过程中,为了方便调试代码,经常会向stdout中输出一些日志,默认的这些日志就直接显示在了终端中.而一般的应用服务器,第三方库,甚至服务器的一些通告也会在终端中显示,这样就搅乱了我们想要的信 ...

  10. linux系统快速查看进程pid的方法

    一个很简单的命令,pgrep,可以迅速定位包含某个关键字的进程的pid:使用这个命令,再也不用ps aux 以后去对哪个进程的pid了 一个很简单的命令,pgrep,可以迅速定位包含某个关键字的进程的 ...

随机推荐

  1. linuxz中压缩解压缩文件

    压缩解压缩.tar格式文件: 把文件打包为tar.gz命令: tar -zcvf 文件名.tar.gz 要压缩的文件/文件夹                                      ...

  2. 13-之容器资源需求、资源限制及Metric-server(Heapster)

    目录 容器资源需求.资源限制及Heapster Heapster 资源指标API及自定义指标API k8s-promtheus监控部署 node-exporter prometheus kube-st ...

  3. spark闭包检查

    spark在执行算子时,如果算子内部用到了外部(Driver)端的对象或变量,就一定会出现闭包:spark在执行算子之前会进行闭包检查,也就是对外部对象或变量进行序列化检查:

  4. PIL修改图像

    PIL修改图像 像素:最小物理单元 pixel 分辨率:1024*980 可以表征 图像分辨率 或者350dpi 每英寸 350个dot表征分辨率 调整图像分辨率 from PIL import Im ...

  5. Unity 读取Json文件、创建Json文件

    using System.IO; using UnityEngine; public class ReadJson:MonoBehaviour { public static TestSetting ...

  6. RTC@@@Real-Time Clock(实时时钟的简称)及电路问题分析

    RTC@@@Real-Time Clock(实时时钟的简称) 实时时钟(Real-Time Clock)是PC主板上的晶振及相关电路组成的时钟电路的生成脉冲,提供稳定的时钟信号给后续电路用.主要功能有 ...

  7. (转载)私人问卷收集系统-Surveyking问卷收集系统

    前言 但凡提及问卷收集系统,问卷星与腾讯问卷通常都为大家首选问卷调查系统. 担心数据安全,海量问卷管理不便,工作流创建困难?快速部署自有问卷调查系统开始你的问卷调查之旅. 无论是问卷调查,考试系统,公 ...

  8. ConvTranspose的output_padding问题

    当stride>=2时,反向传播,由dy, w得到dx的时候,dx的形状不唯一. 例如input_shape (7,7)或者(8,8)在kernel(3,3)上,以stride=2进行卷积, 最 ...

  9. Entity Framework生成的SQL语句

    var Query= database.Table1.Find(cond, f => f.Table2, f => f.Table3, f => f.Table4, f => ...

  10. SPI接口(续一)

    SPI接口共涉及到11个寄存器,下面就来对它们进行具体分析. 先来看SPI配置寄存器CFG,下表是它的全部位结构,其地址分别为0x40058000(SPI0),0x4005C000(SPI1). (1 ...