| import requests |
| import time |
| from datetime import datetime |
| import logging |
|
|
| |
| logging.basicConfig( |
| level=logging.INFO, |
| format='%(asctime)s - %(message)s', |
| handlers=[ |
| logging.StreamHandler(), |
| logging.FileHandler('ip_log.txt') |
| ] |
| ) |
|
|
| def get_ip(): |
| try: |
| |
| services = [ |
| 'https://api.ipify.org?format=json', |
| 'https://ifconfig.me/ip', |
| 'https://api.myip.com' |
| ] |
| |
| for service in services: |
| try: |
| response = requests.get(service, timeout=5) |
| if response.status_code == 200: |
| if service.endswith('json'): |
| return response.json()['ip'] |
| return response.text.strip() |
| except: |
| continue |
| |
| return "无法获取IP" |
| except Exception as e: |
| return f"错误: {str(e)}" |
|
|
| def main(): |
| logging.info("IP 监控已启动") |
| |
| while True: |
| ip = get_ip() |
| logging.info(f"当前IP: {ip}") |
| |
| |
| time.sleep(60) |
|
|
| if __name__ == "__main__": |
| main() |