Create monitor_ip.py
Browse files- monitor_ip.py +50 -0
monitor_ip.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import time
|
| 3 |
+
from datetime import datetime
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
# 配置日志
|
| 7 |
+
logging.basicConfig(
|
| 8 |
+
level=logging.INFO,
|
| 9 |
+
format='%(asctime)s - %(message)s',
|
| 10 |
+
handlers=[
|
| 11 |
+
logging.StreamHandler(), # 输出到控制台
|
| 12 |
+
logging.FileHandler('ip_log.txt') # 输出到文件
|
| 13 |
+
]
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
def get_ip():
|
| 17 |
+
try:
|
| 18 |
+
# 尝试多个 IP 查询服务,以防某个服务不可用
|
| 19 |
+
services = [
|
| 20 |
+
'https://api.ipify.org?format=json',
|
| 21 |
+
'https://ifconfig.me/ip',
|
| 22 |
+
'https://api.myip.com'
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
for service in services:
|
| 26 |
+
try:
|
| 27 |
+
response = requests.get(service, timeout=5)
|
| 28 |
+
if response.status_code == 200:
|
| 29 |
+
if service.endswith('json'):
|
| 30 |
+
return response.json()['ip']
|
| 31 |
+
return response.text.strip()
|
| 32 |
+
except:
|
| 33 |
+
continue
|
| 34 |
+
|
| 35 |
+
return "无法获取IP"
|
| 36 |
+
except Exception as e:
|
| 37 |
+
return f"错误: {str(e)}"
|
| 38 |
+
|
| 39 |
+
def main():
|
| 40 |
+
logging.info("IP 监控已启动")
|
| 41 |
+
|
| 42 |
+
while True:
|
| 43 |
+
ip = get_ip()
|
| 44 |
+
logging.info(f"当前IP: {ip}")
|
| 45 |
+
|
| 46 |
+
# 等待60秒
|
| 47 |
+
time.sleep(60)
|
| 48 |
+
|
| 49 |
+
if __name__ == "__main__":
|
| 50 |
+
main()
|