1. 程式人生 > >Linux 項目 shell 自動獲取報告本機IP (1) | 通過shell 自動獲取報告本機IP

Linux 項目 shell 自動獲取報告本機IP (1) | 通過shell 自動獲取報告本機IP

execute bin -s smtp each substr linu while ces

由於電腦設置靜態IP經常出現鏈接不上網絡,動態IP又非常不方便,故有了這個想法並實現

原理:

  Linux,包含PC機器,樹莓派等,通過shell 自動獲取報告本機IP | 通過 Mutt+Msmtp郵箱發送

此次使用樹莓派3B實現步驟:

1.安裝mutt 和 Msmtp

$ sudo apt -get install mutt   //安裝mutt,其他系統使用相應包管理

$ sudo apt-get install msmtp   //安裝msmtp,其他系統使用相應包管理

2.在/etc/Muttrc 下配置 mutt

##2019 1 25 send ip to my mail
set sendmail="/usr/bin/msmtp" set use_from=yes set realname=" Pi‘s address4 " set from = A 郵箱地址 set envelope_from=yes set crypt_use_gpgme = no

3.在/root/下 新建配置msmtp

account default
host smtp.aliyun.com                
from your A mail @aliyun.com
auth plain
user your A mail @aliyun.com   
//A郵箱地址 password 密碼 logfile ~/.msmtp.log // 存儲日誌

4.編寫shell 獲取 ip 並發送

# 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 [ "x$RET_CODE
" = "x200" ]; then echo "Network OK, will send mail..." break else echo "Network not ready, wait..." sleep 1s fi done # get the IP address of eth0 ETH0_IP_ADDR=` ifconfig wlan0 | sed -n "2,2p" | awk {print substr($2,1)} ` ECHO_IP=`ifconfig ` # send the Email echo " test ifconfig wlan0:$ECHO_IP " | mutt -s "Current time:`date ‘+%F %T‘` Raspiberry: $ETH0_IP_ADDR " B 郵箱地址

此時通過運行腳本便可發送 ip 到 B郵箱

5.添加開機自啟動腳本就可實現 -->> 開機啟動的多種方式設置

這次使用 更改/etc/rc.load 方式自啟動,在exit0 上面添加內容

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "My IP address is %s\n" "$_IP"
fi
#在exit0 上面添加內容
su pi -c "source /etc_sh/send_ip_mail.sh"   //shell文件地址
exit 0

Linux 項目 shell 自動獲取報告本機IP (1) | 通過shell 自動獲取報告本機IP