獲取樹莓派內網IP

通常在使用不帶外設輸入輸出設備的樹莓派時(本文是以CentOS7系統爲例),如果不給樹莓派固定靜態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

二、發送:
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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章