获取树莓派内网IP

通常在使用不带外设输入输出设备的树莓派时(或其他Linux系统设备),如果不给树莓派固定静态IP,重启后树莓派IP可能发生变化,由于需要重新确认树莓派IP,找显示器、键盘甚至鼠标等各种操作随之而来,导致重连树莓派的这个过程会非常麻烦。

本人使用邮件通知的方式达到便捷获取树莓派内网IP的目的,编写如下脚本(需要安装sendmail):

send-ip-mail.sh

#!/bin/bash
# Create on 2018/09/11 by Cyril
# check network availability

while true
do
  TIMEOUT=5
  SITE_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" ]; then
        echo "Network OK, will sending mail..."
        break
  else
        echo "Network not ready and not sending mail, waiting 1m..."
        sleep 1m
  fi
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 ."  [email protected]  ##注意此处填写你自己的邮箱

当然只有如上脚本还不能达到目的,还需要把它加入到开机自启名单中。

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/local

ip 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

二、发送:

通过文件内容发送:

mail  -s  '主题'  [email protected]  <  test.txt 

通过管道符直接发送:

echo  '内容'  |  mail  -s  '主题'  [email protected]

三、设置发件人信息:vim /etc/mail.rc

set [email protected]
set smtp=smtp.163.com
set smtp-auth-user=用户名
set smtp-auth-password=密码
set smtp-auth=login

四、查看队列:

mailq

五、查看日志:

tail  /var/log/maillog

猜你喜欢

转载自blog.csdn.net/u011865919/article/details/83957913