[树莓派]获取公网IP地址并提醒IP地址变更
curl ifconfig.me curl icanhazip.com curl curlmyip.com curl ip.appspot.com curl ipinfo.io/ip curl ipecho.net/plain curl www.trackip.net/i #补充 curl ip.sb curl ip.6655.com/ip.aspx curl whatismyip.akamai.com wget -qO - ifconfig.co dig +short myip.opendns.com @resolver1.opendns.com curl ident.me curl v4.ident.me curl v6.ident.me curl inet-ip.info #返回IP和地区 curl ip.6655.com/ip.aspx?area=1 curl 1111.ip138.com/ic.asp curl ip.cn curl cip.cc
博主用的树莓派4B,家里拉的是广电的网络,有一个动态公网IP地址。博主用树莓派做个服务器+NAS。我在外地上学,家人也不会看IP,只能做一个IP地址变更的脚本来告诉自己IP变成了啥。用python写的。
import os import requests import time import smtplib from email.mime.text import MIMEText from email.header import Header def get_public_ip(): try: # 获取IP地址 url='https://api.ipify.org/' resp = requests.get(url) public_ip = resp.text print(public_ip) except Exception as e: print(e) return public_ip def text_write(name,msg): # 写入IP file_path = '/home/pi/xxxx/' # 新创建的txt文件的存放路径 这里替换为自己的路径即可 full_path = file_path + name + '.txt' file = open(full_path, 'w') file.write(msg) file.close() def text_read(name): # 读取IP file_path = '/home/pi/xxxx/' full_path = file_path + name + '.txt' file = open(full_path, 'r') ip = file.read() file.close() return ip def sendMsgBySmtp(mail, title, msg): ret = "SMTP邮件发送成功" try: if mail == '': return '邮箱为空,已取消SMTP发送!' # 发信方的信息:发信邮箱,邮箱授权码 from_addr = "xxx" # 发信方邮箱账号 password = 'xxxx' # 发信方邮箱密码 if from_addr == '': return '发信邮箱地址为空,已取消SMTP发送!' if password == '': return '发信邮箱密码为空,已取消SMTP发送!' # 收信方邮箱 to_addr = mail # 发信服务器 smtp_server = 'smtp.163.com' if smtp_server == '': return '发信邮箱服务器为空,已取消SMTP发送!' # 邮箱正文内容,第一个参数为内容,第二个参数为格式(plain 为纯文本),第三个参数为编码 msg = MIMEText(msg, 'plain', 'utf-8') # 邮件头信息 h = Header('树莓派', 'utf-8') # 允许自定义发信邮箱地址,需注意收信方安全策略问题 h.append(from_addr, 'ascii') msg['From'] = h msg['To'] = Header(to_addr) msg['Subject'] = Header(title) # 开启发信服务,这里使用的是加密传输 server = smtplib.SMTP_SSL(smtp_server, 465) # 登录发信邮箱 server.login(from_addr, password) # 发送邮件 server.sendmail(from_addr, to_addr, msg.as_string()) # 关闭服务器 server.quit() except Exception as e: # 如果try中的语句没有执行,则会执行下面的ret=False ret = "SMTP邮件发送失败,%s" % (e) else: print(ret) return ret def main(): old_ip = text_read('myip') new_ip = get_public_ip() if (new_ip != old_ip): #check_ip_change(new_ip, old_ip) text_write('myip', new_ip) print("Saved new ip!") sendMsgBySmtp('这里填接收邮件的邮箱','IP变更提醒',f"IP变更为:{new_ip}") print("Send new ip by mail!") else: # ext_write('myip', old_ip) print("The IP has not changed!") main() # def main(): # schedule.every().day.at("17:03").do(job) # while True: # schedule.run_pending() # time.sleep(1)
博主用树莓派crontab定时执行。
定时执行的命令crontab -e
这是手动执行的结果IP没有变更,所以是下面的内容。
如果IP地址变更了也不需要我们去手动更改存IP地址的TXT文件,脚本会帮我们自动更改为新IP。