1. 程式人生 > >獲取樹莓派內網IP

獲取樹莓派內網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