已持有树莓派近两年,包括家喻户晓的edup-n8508gs无线网卡。
最近想观察一下邻居的wifi使用情况,于是写个(bash)shell这样做:
1.扫描无线网络
str=`sudo iwlist wlan0 scan`(假设无线网卡接口名称是wlan0)
结果是:
wlan0 Scan completed :Cell 01 - Address: F8:DF:A8:F2:XX:XXESSID:"ChinaNet-xxxx"Protocol:IEEE 802.11bgnMode:MasterFrequency:2.412 GHz (Channel 1)Encryption key:onBit Rates:130 Mb/sExtra:wpa_ie=dd160050f20101000050f20401000050f20401000050f202IE: WPA Version 1Group Cipher : CCMPPairwise Ciphers (1) : CCMPAuthentication Suites (1) : PSKExtra:rsn_ie=30140100000fac040100000fac040100000fac020000IE: IEEE 802.11i/WPA2 Version 1Group Cipher : CCMPPairwise Ciphers (1) : CCMPAuthentication Suites (1) : PSKIE: Unknown: DD710050F204104A0001101044000102103B000103104700106304125310192006122800D24C819881102100037A7465102300036F6E751024000745562D323031321042000F3132333435363738393031323334371054000800060050F2040001101100036F6E7510080002018C103C000101Quality=83/100 Signal level=42/100Cell 02 - Address: F0:EB:D0:80:xx:xxESSID:"PHICOMM_xxxxxx"Protocol:IEEE 802.11bgnMode:MasterFrequency:2.412 GHz (Channel 1)Encryption key:onBit Rates:300 Mb/sExtra:wpa_ie=dd180050f20101000050f20401000050f20401000050f2020c00IE: WPA Version 1Group Cipher : CCMPPairwise Ciphers (1) : CCMPAuthentication Suites (1) : PSKExtra:rsn_ie=30140100000fac040100000fac040100000fac020c00IE: IEEE 802.11i/WPA2 Version 1Group Cipher : CCMPPairwise Ciphers (1) : CCMPAuthentication Suites (1) : PSKQuality=100/100 Signal level=56/100......
2.截取数据
以"Cell"作为各个无线的划分词,由于"cut -d "不支持字符串,先把"Cell"替换为单个字符"@",再划分:
s=${str//Cell/@}
sp=`echo $s|cut -d "@" -fN` (第N段)
然后对每条cell内容取出想要的数据,如热点名称Essid、设备地址Address、信号级别SignalLevel等。
这是取Address:
echo $sp | sed -r 's/.*Address: (.*)ESSID/\1/'
3.保存数据
存到平面文本也行,这里为了以后查询方便,用mysql保存。
建表:(对单个address来说,essid事实上很少变化,所以这个表设计是不好的)
CREATE TABLE `wifi` (`addr` char(17) DEFAULT NULL,`essid` varchar(50) DEFAULT NULL,`sgnlvl` tinyint(4) DEFAULT NULL,`dt` datetime DEFAULT NULL)
单次扫描所得数据一次性插入:
insert into wifi (addr,essid,sgnlvl,dt)select addr1,xxx,xxx,xxxunion allselect addr2,xxx,xxx,xxx......
4.定时重复
while true;do
scan
sleep 1800 #(秒)
done
一看便知
结果:
运行一段时间后发现:
稳定扫描出的无线有8个,几乎都是300M的,几乎都是全天开着的。
有两个特别一点:
一个是phicomm的,每次凌晨4点到6点这段时间都扫描不到。查看产品说明,有智能增益控制,估计是有用户连接时信号增强,一段时间后没连接则信号减弱。那就可以推断此用户一般6点起床(上班),而中秋三天则4点到9点这段空白,放假就睡晚点咯。
另一个是tplink的,上班非休息时间就扫描不到,时间段也不是非常有规律,估计用户出门前有关机习惯。
完整代码:
getCell(){addr=`echo "$1"|sed -r 's/.*Address: (.*) ESSID.*/\1/'`essid=`echo "$1"| sed -r 's/.*ESSID:"(.*)" Protocol.*/\1/'`sgnlvl=`echo "$1" | sed -r 's/.*Signal level=(.*)\/100.*/\1/'`echo "select '$addr','$essid',$qlty,$sgnlvl,'$2'"
}scan(){str=`sudo iwlist wlan0 scan`s=${str//Cell/@}i=2sql="insert into wifi (addr,essid,qlty,sgnlvl,dt) "dt=`date '+%Y-%m-%d %T'`while true;dosp=`echo $s|cut -d "@" -f$i`if [ "$sp" != "" ]thenret=`getCell "$sp" "$dt"`sql="$sql $ret union all "((i++))elsesql=${sql%'union all '}mysql -u root -ppassword -e "use stat;$sql"breakfi
done
}while true;doscansleep 1800
done