玩转树莓派[07开机后将 IP 地址信息自动推送到微信]

树莓派经常会用到查看本机的IP,知道了 IP 地址才能进行 ssh 远程连接。以前用过使用Python 获取树莓派地址+Email 发送到自己的邮箱,方法是可行的。但是这里使用了更加简便的方法,使用 Python 加上 Server酱服务, Server酱 服务实现了通过请求 URL + 推送信息,的方式来把消息推送到微信。省去了去配置邮箱参数的麻烦,而且通过微信可以更加快捷的查看到推送到微信的IP信息。

代码

import time
import socket
import requests
def getLocalIP():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('1.1.1.1', 80))
    ipaddr = s.getsockname()[0]
    s.close()
    return ipaddr
def post(ip):
    url = "https://sc.ftqq.com/your~sckey.send"
    data = "text=%s" % ip
    results = requests.get(url, data)
    print(results)
if __name__ == '__main__':
    time.sleep(20)
    while True:
        ip = getLocalIP()
        if ip == False:
            post('finding ip ~')
        else:
            print(ip)
            post(ip)
            time.sleep(5)
        break

配置开机自启动

pi@raspbian:/$ cat /boot/rc-local
#!/bin/bash

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "IP address is %s\n" "$_IP"
fi

echo "rc-local bash echo test."
sleep 1m
python /home/pi/ip_send.py
exit 0

参考

posted @ 2022-10-10 21:50  baixf白小飞  阅读(82)  评论(0编辑  收藏  举报