Update monitor_ip.py
Browse files- monitor_ip.py +25 -21
monitor_ip.py
CHANGED
|
@@ -1,38 +1,40 @@
|
|
|
|
|
| 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 |
-
#
|
| 19 |
-
|
| 20 |
-
'https://api.ipify.org?format=json',
|
| 21 |
-
'https://ifconfig.me/ip',
|
| 22 |
-
'https://api.myip.com'
|
| 23 |
-
]
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
except Exception as e:
|
| 37 |
return f"错误: {str(e)}"
|
| 38 |
|
|
@@ -40,8 +42,10 @@ def main():
|
|
| 40 |
logging.info("IP 监控已启动")
|
| 41 |
|
| 42 |
while True:
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
| 45 |
|
| 46 |
# 等待60秒
|
| 47 |
time.sleep(60)
|
|
|
|
| 1 |
+
import socket
|
| 2 |
import requests
|
| 3 |
import time
|
| 4 |
from datetime import datetime
|
| 5 |
import logging
|
| 6 |
|
|
|
|
| 7 |
logging.basicConfig(
|
| 8 |
level=logging.INFO,
|
| 9 |
format='%(asctime)s - %(message)s',
|
| 10 |
handlers=[
|
| 11 |
logging.StreamHandler(), # 输出到控制台
|
| 12 |
+
logging.FileHandler('/tmp/ip_log.txt') # 输出到文件
|
| 13 |
]
|
| 14 |
)
|
| 15 |
|
| 16 |
def get_ip():
|
| 17 |
try:
|
| 18 |
+
# 创建一个 UDP 套接字
|
| 19 |
+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
# 连接到一个外部服务器(不需要真正建立连接)
|
| 22 |
+
s.connect(("8.8.8.8", 80))
|
| 23 |
+
|
| 24 |
+
# 获取本地 IP
|
| 25 |
+
ip = s.getsockname()[0]
|
| 26 |
+
|
| 27 |
+
s.close()
|
| 28 |
+
return ip
|
| 29 |
+
except Exception as e:
|
| 30 |
+
return f"错误: {str(e)}"
|
| 31 |
+
|
| 32 |
+
def get_public_ip():
|
| 33 |
+
try:
|
| 34 |
+
# 使用 DNS 解析来获取当前域名的 IP
|
| 35 |
+
hostname = socket.gethostname()
|
| 36 |
+
ip = socket.gethostbyname(hostname)
|
| 37 |
+
return ip
|
| 38 |
except Exception as e:
|
| 39 |
return f"错误: {str(e)}"
|
| 40 |
|
|
|
|
| 42 |
logging.info("IP 监控已启动")
|
| 43 |
|
| 44 |
while True:
|
| 45 |
+
local_ip = get_ip()
|
| 46 |
+
public_ip = get_public_ip()
|
| 47 |
+
logging.info(f"本地IP: {local_ip}")
|
| 48 |
+
logging.info(f"公网IP: {public_ip}")
|
| 49 |
|
| 50 |
# 等待60秒
|
| 51 |
time.sleep(60)
|