import subprocess import time from datetime import datetime import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(message)s', handlers=[ logging.StreamHandler(), logging.FileHandler('/tmp/ip_log.txt') ] ) def get_ip(): try: # 使用 curl 直接访问实际的 IP 地址 cmd = "curl -s http://eth0.me" # 或者使用 curl -s ifconfig.me result = subprocess.check_output(cmd, shell=True).decode('utf-8').strip() return result except Exception as e: return f"错误: {str(e)}" def get_network_info(): try: # 获取更详细的网络信息 cmd = "ip addr show" result = subprocess.check_output(cmd, shell=True).decode('utf-8') return result except Exception as e: return f"错误: {str(e)}" def main(): logging.info("IP 监控已启动") while True: ip = get_ip() logging.info(f"公网IP: {ip}") # 每小时记录一次详细的网络信息 if datetime.now().minute == 0: network_info = get_network_info() logging.info(f"网络详情:\n{network_info}") time.sleep(60) if __name__ == "__main__": main()