python操作 linux连接wifi,查看wifi连接状态方法
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连接状态方法的更多相关文章
- python操作mongodb根据_id查询数据的实现方法
python操作mongodb根据_id查询数据的实现方法 python操作mongodb根据_id查询数据的实现方法,实例分析了Python根据pymongo不同版本操作ObjectId的技巧, ...
- linux中可以查看端口占用的方法
在自己搭建的服务器中,经常容易出现端口被占用的问题,那么怎么知道自己的端口是否被占用了呢? 可以使用下面的方法: linux中可以查看端口占用的方法. netstat -ant | grep 80 ( ...
- 在Linux终端中查看公有IP的方法详解
首先回顾一下一般的查看IP的命令: ifconfigLinux查看IP地址的命令--ifconfigifconfig命令用于查看和更改网络接口的地址和参数 $ifconfig -a lo0: fla ...
- python操作文件和目录查看、创建、删除、复制
python内置了os模块可以直接调用操作系统提供的接口函数,os.name查询的是操作系统,‘nt’表示windows系统 >>> import os >>> o ...
- linux设置和查看环境变量的方法
1. 显示环境变量HOME $ echo $HOME /home/redbooks 2. 设置一个新的环境变量hello $ export HELLO="Hello!" ...
- Linux设置和查看环境变量的方法 详解
1. 显示环境变量HOME $ echo $HOME /home/redbooks 2. 设置一个新的环境变量hello $ export HELLO="Hello!" $ ech ...
- python 下载.whl 文件,查看已安装软件包方法
下载地址 https://www.lfd.uci.edu/~gohlke/pythonlibs/ 另一个Python packages地址为 https://pypi.org/ 下载 ...
- 【转】Linux设置和查看环境变量的方法
转: http://www.jb51.net/LINUXjishu/77524.html 1. 显示环境变量HOME $ echo $HOME /home/redbooks 2. 设置一个新的环境变量 ...
- python在linux中输出带颜色的文字的方法
在开发项目过程中,为了方便调试代码,经常会向stdout中输出一些日志,默认的这些日志就直接显示在了终端中.而一般的应用服务器,第三方库,甚至服务器的一些通告也会在终端中显示,这样就搅乱了我们想要的信 ...
- linux系统快速查看进程pid的方法
一个很简单的命令,pgrep,可以迅速定位包含某个关键字的进程的pid:使用这个命令,再也不用ps aux 以后去对哪个进程的pid了 一个很简单的命令,pgrep,可以迅速定位包含某个关键字的进程的 ...
随机推荐
- json 解析,JSON数组
public class resuleobj { public int returncode { get; set; } public string message { get; set; } pub ...
- absible笔记第一章 (ansibles基础与playbook常用模块)
一. ansibles基础与playbook 1.优先级问题 ANSIBLE_CONFIG ansible.cfg 项目目录 ...
- 学习-自增id++的问题
代码示例: let id = 0 const todos = ref([ { id: id++, text: 'Learn HTML' }, { id: id++, text: 'Lear ...
- 运行Django项目报错
运行 pip install -r requirements.txt -i https://pypi.douban.com/simple
- MySQL表操作(上篇)
1.存储引擎的介绍 (1)存储引擎 1.什么是存储引擎? mysql中建立的库===>文件夹 库中建立的表===>文件 现实生活中我们用来存储数据的文件有不同的类型,每种文件类型对应各自不 ...
- laravel Auth的使用
最新的文档是使用的 laravel/jetstream 扩展包,旧版本中的 php artisan make:auth 命令在新版本中已不能用,但是此博客没有使用文档提供的扩展包,而是使用的是lara ...
- git diff如何确定差异所在函数context
问题 在使用git diff 展示c/c++文件修改内容时,除了显示修改上下文外,输出还贴心的展示了修改所在的函数.尽管这个展示并不总是准确,但是能够做到大部分情况下准确也已经相当不错:是不是git内 ...
- java & spring 注解 备忘
java deprecated 注解 1 /** 2 * General service for all common business logic. 3 * 4 * @author wanghaip ...
- v4l2编程
一.video 4 linux 2 ,是linux中关于视频设备的内核驱动.在linux中,视频设备是设备文件,可以像访问普通文件一样对其进行读写,摄像头在/dev/video 0下 二一般操作流程( ...
- Rsync等传统文件同步方式已过时 如何寻找替代产品?
Rsync原本是在Linux系统下面的一个文件同步协议,随着技术的发展,它也有其它版本的,如Windows和AIX.HPUX下面都有相应的版本可以支持的.它有很多版本都是免费的,配置也不复杂,所以很多 ...