1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import requests def get_public_ip(): try: response = requests.get('https://api.ipify.org?format=json') response.raise_for_status() ip_info = response.json() return ip_info['ip'] except requests.RequestException as e: print(f"Error fetching public IP: {e}") return None
public_ip = get_public_ip() if public_ip: print(f"Public IP Address: {public_ip}")
|
一个实际案例来展示该工具的应用。检查本机外网IP是否发生了变化,如果发生变化,就通过邮件通知。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| <PYTHON> import requests
def get_ip(): try: response = requests.get('https://api.ipify.org?format=json') response.raise_for_status() ip_info = response.json() return ip_info['ip'] except requests.RequestException as e: print(f"Error fetching public IP: {e}") return None
current_ip = get_ip()
import smtplib from email.mime.text import MIMEText from email.header import Header
sender = "sender@example.com" receiver = "receiver@example.com"
password = "your_password"
if current_ip: try: with open("ip.txt", "r") as f: last_ip = f.read().strip() except FileNotFoundError: last_ip = ""
if current_ip != last_ip: message = MIMEText(f"Your public IP has changed to {current_ip}", "plain", "utf-8") message["From"] = Header("IP Monitor", "utf-8") message["To"] = Header("You", "utf-8") message["Subject"] = Header("IP Address Change Notification", "utf-8")
try: smtp_obj = smtplib.SMTP("smtp.example.com", 587) smtp_obj.starttls() smtp_obj.login(sender, password) smtp_obj.sendmail(sender, receiver, message.as_string()) smtp_obj.quit() print("邮件发送成功") except smtplib.SMTPException as e: print(f"邮件发送失败:{e}")
with open("ip.txt", "w") as f: f.write(current_ip) else: print("无法获取当前的外网 IP 地址")
|