raspberry pi 开机wifi自动启动并发邮件通知

jackxiang 2013-8-20 21:33 | |

raspberry pi 开机wifi自动启动并发邮件通知
 安装好USB的wifi模块,自动获取IP地址。获取到IP后邮件通知。这样每次重启就不用再连显示器了。
以下几个的安装是为了方便使用与本次无关。
安装vim
$ sudo apt-get install vim
将时区改为上海
$ sudo cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
安装校时工具
$ sudo apt-get install ntpdate
通过网络同步时间
$ /usr/sbin/ntpdate stdtime.gov.hk
  把USB的wifi接口接好。
  我接了一个腾达W311M的wifi无线,用命令看到无线网卡已经加载。如下:
$ lsusb
Bus 001 Device 004: ID 148f:5370 Ralink Technology, Corp. RT5370 Wireless Adapter
image
  然后可以在图形化界面中wpa_gui配置。如果使用命令行可以用wpa_cli。我是直接修改配置文件。我的配置文件如下:
无线配置文件位置/etc/wpa_supplicant/wpa_supplicant.conf
文件内容如下:
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=0
network={
ssid=”simonzhang”
psk=”xxxxxxx”
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP
auth_alg=OPEN
}
网络部分配置/etc/network/interface
文件内容如下:
auto lo
iface lo inet loopback
iface eth0 inet dhcp
allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
  配置完毕,将启动后发送邮件的脚本放到家目录中,脚本如下,如果邮件服务器认证不严的话用sendmail会更简单:
#!/bin/env python
# -*- coding:utf-8 -*-
# -------------------------------
# Filename:  
# Revision:
# Date:        2012-12-5
# Author:      simonzhang
# Email:       simon-zzm@163.com
# Web:         www.simonzhang.net
# -------------------------------
import os
import time
import socket
import fcntl
import struct
import smtplib
from email.mime.text import MIMEText
mail_host = 'smtp.exmail.qq.com'
mail_user = 'xxxxxxx'
mail_pwd = 'xxxxxxx'
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        return socket.inet_ntoa(fcntl.ioctl(
            s.fileno(),
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', ifname[:15])
         )[20:24])
    except IOError, e:
        return e
def mail_send(content, mailto, get_sub):
    msg = MIMEText(content.encode('utf8'), _subtype='html',  _charset='utf8')
    msg['From'] = mail_user
    msg['Subject'] = u'%s' % get_sub
    msg['To'] = mailto
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pwd)
        s.sendmail(mail_user,[mailto],msg.as_string())
        s.close()
        send = "OK"
    except Exception ,e:
        send = "ERROR! %s" % e
    return send
def main():
    _count_loop = 0
    while 1:
        ip_list = []
        if _count_loop == 0:
            os.system('sudo wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf')
            time.sleep(0.5)
            os.system('sudo dhclient wlan0')
        try:
            ip_list.append(get_ip_address('eth0'))
        except:
            pass
        try:
            ip_list.append(get_ip_address('wlan0'))
        except Except,e:
            pass
        _get_send_status =  mail_send('my pi ip', 'simon-zzm@163.com', '%s' % ip_list)
        _count_loop +=1
        if (_get_send_status == "OK") or (_count_loop == 3):
            break
        time.sleep(3)
if __name__ == "__main__":
    main()
  脚本测试通过,配置开机启动。
$ sudo vim /etc/rc.local
# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
printf “My IP address is %s\n” “$_IP”
fi
# start wifi
echo “Starting WiFi…”
wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf
sleep .5s
dhclient wlan0
echo “WiFi should be started”
# notification my ip
python /home/pi/script/NotificationIP.py
exit 0
失败经验总结:
1)之前是用的下面代码,但是在除掉网线后路由里的默认网关没有,用“sudo route add default gw 192.168.1.1”添加,如果有网线只是报有一个ip。
def get_local_ip_address():
ipaddr = ”
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((’1.1.1.1′, 8000))
ipaddr = s.getsockname()[0]
s.close()
except:
ipaddr = “ERROR”
return ipaddr
2)系统应该不支持热插拔,每次查usb wifi时都会重启。
3)不知道是电力原因,还是USB wifi原因,连接质量很不好,容易断开。
参考文档:
http://stinebaugh.info/auto-start-your-wifi-on-raspberry-pi/
raspberry pi 开机wifi自动启动并发邮件通知
比之前脚本添加了,测试公网IP的函数。
def get_global_ip():
get_html = urllib2.urlopen(‘http://iframe.ip138.com/ic.asp’).read()
_re_ip = re.compile(r’\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}’, re.DOTALL)
_global_ip = _re_ip.findall(get_html)[0]
return _global_ip
代码:NotificationIP.py
#!/bin/env python
# -*- coding:utf-8 -*-
# -------------------------------
# Filename:  
# Revision:    2.0
# Date:        2012-12-5
# Author:      simonzhang
# Email:       simon-zzm@163.com
# Web:         www.simonzhang.net
#
# 1.0 create script
# 2.0 add check global ip  
# -------------------------------
import os
import re
import urllib2
import time
import socket
import fcntl
import struct
import smtplib
from email.mime.text import MIMEText
mail_host = 'smtp.exmail.qq.com'
mail_user = 'warning@qq.net'
mail_pwd = 'aaabbbb'
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        return socket.inet_ntoa(fcntl.ioctl(
            s.fileno(),
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', ifname[:15])
         )[20:24])
    except IOError, e:
        return e
def get_global_ip():
    get_html =  urllib2.urlopen('http://iframe.ip138.com/ic.asp').read()
    _re_ip = re.compile(r'\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', re.DOTALL)
    _global_ip = _re_ip.findall(get_html)[0]
    return _global_ip
def mail_send(content, mailto, get_sub):
    msg = MIMEText(content.encode('utf8'), _subtype='html',  _charset='utf8')
    msg['From'] = mail_user
    msg['Subject'] = u'%s' % get_sub
    msg['To'] = mailto
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pwd)
        s.sendmail(mail_user,[mailto],msg.as_string())
        s.close()
        send = "OK"
    except Exception ,e:
        send = "ERROR! %s" % e
    return send
def main():
    _count_loop = 0
    while 1:
        ip_list = []
    #    if _count_loop == 0:
    #        os.system('sudo wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf')
    #        time.sleep(0.5)
    #        os.system('sudo dhclient wlan0')
        try:
            ip_list.append("eth0: %s" % get_ip_address('eth0'))
        except:
            pass
        try:
            ip_list.append("wlan0: %s" % get_ip_address('wlan0'))
        except Except,e:
            pass
        try:
            _global_ip = get_global_ip()
            ip_list.append('global ip: %s' % _global_ip)
        except :
            pass
        _get_send_status =  mail_send('my pi ip', 'simon-zzm@139.com', '%s' % ip_list)
        _count_loop +=1
        if (_get_send_status == "OK") or (_count_loop == 3):
            break
        time.sleep(3)
if __name__ == "__main__":
    main()
来自:http://www.simonzhang.net/?p=1501
http://www.simonzhang.net/?p=1668

作者:jackxiang@向东博客 专注WEB应用 构架之美 --- 构架之美,在于尽态极妍 | 应用之美,在于药到病除
地址:http://jackxiang.com/post/6607/
版权所有。转载时必须以链接形式注明作者和原始出处及本声明!


最后编辑: jackxiang 编辑于2013-8-20 21:34
评论列表
发表评论

昵称

网址

电邮

打开HTML 打开UBB 打开表情 隐藏 记住我 [登入] [注册]