本文主要是介绍获取树莓派内网IP,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
通常在使用不带外设输入输出设备的树莓派时(本文是以CentOS7系统为例),如果不给树莓派固定静态IP,重启后树莓派IP可能发生变化,由于需要重新确认树莓派IP,找显示器、键盘甚至鼠标等各种操作随之而来,导致重连树莓派的这个过程会非常麻烦。
本人使用邮件通知的方式达到便捷获取树莓派内网IP的目的,编写如下脚本(需要安装sendmail):
send-ip-mail.sh
#!/bin/bash
# Create on 2018/09/11 by Cyril
# check network availabilitywhile true
doTIMEOUT=5SITE_TO_CHECK="www.163.com"RET_CODE=`curl -I -s --connect-timeout $TIMEOUT $SITE_TO_CHECK -w %{http_code} | tail -n1`if [ "$RET_CODE" = "200" ]; thenecho "Network OK, will sending mail..."breakelseecho "Network not ready and not sending mail, waiting 1m..."sleep 1mfi
done# get the IP address of eth0, e.g. "192.168.16.5"
ETH0_IP_ADDR=`ifconfig eth0 | sed -n "2,2p" | awk '{print substr($2,1)}'` #本地连接ip
WLAN0_IP_ADDR=`ifconfig wlan0 | sed -n "2,2p" | awk '{print substr($2,1)}'` #无线连接ip# send the Email
echo "
Hi Cyril,Your RaspberryPi is login in.
Login Time: `date '+%F %T'`.
Login IP:(ETH0)$ETH0_IP_ADDR(WLAN0)$WLAN0_IP_ADDR
Have a good day.
[From my RaspberryPi.]
" | mail -s "RaspberryPi is login in $WLAN0_IP_ADDR ." 848873227@qq.com ##注意此处填写你自己的邮箱
当然只有如上脚本还不能达到目的,还需要把它加入到开机自启名单中。
vi /etc/rc.d/rc.local
ps:我贴出了自己的配置文件内容, 大家配置的时候只需在文末加上‘/root/send-ip-mail.sh &’,保存退出即可,不需要关注其它。
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.touch /var/lock/subsys/localip link set wlan0 up
systemctl stop NetworkManager
wpa_supplicant -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf&
dhclient wlan0
sleep 1/root/send-ip-mail.sh & ## 它将在centos系统开机后自启运行。'&'用在此处是为避免这个任务陷入死循环而影响之后的开机自启项任务
你现在可以重启系统验证,查看邮箱是否成功收到ip。
====================================================
安装sendmail的步骤(以centos7系统为例):
一、安装:
安装sendmail:
yum -y install sendmail
systemctl start sendmail
安装mailx:
yum install -y mailx
二、发送:
mailx可以不用进行发件人信息的配置,但这样发送出去的邮件很可能被收件箱当作垃圾邮件而拒收。
通过文件内容发送:
mail -s '主题' complet@163.com < test.txt
通过管道符直接发送:
echo '内容' | mail -s '主题' complet@163.com
三、设置发件人信息:vim /etc/mail.rc
set from=complet@163.com
set smtp=smtp.163.com
set smtp-auth-user=用户名
set smtp-auth-password=密码
set smtp-auth=login
四、查看队列:
mailq
五、查看日志:
tail /var/log/maillog
这篇关于获取树莓派内网IP的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!