Update monitor_ip.py
Browse files- monitor_ip.py +22 -24
monitor_ip.py
CHANGED
|
@@ -1,38 +1,32 @@
|
|
| 1 |
-
import
|
| 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 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
return response.text.strip()
|
| 32 |
-
except:
|
| 33 |
-
continue
|
| 34 |
-
|
| 35 |
-
return "无法获取IP"
|
| 36 |
except Exception as e:
|
| 37 |
return f"错误: {str(e)}"
|
| 38 |
|
|
@@ -41,9 +35,13 @@ def main():
|
|
| 41 |
|
| 42 |
while True:
|
| 43 |
ip = get_ip()
|
| 44 |
-
logging.info(f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
-
# 等待60秒
|
| 47 |
time.sleep(60)
|
| 48 |
|
| 49 |
if __name__ == "__main__":
|
|
|
|
| 1 |
+
import subprocess
|
| 2 |
import time
|
| 3 |
from datetime import datetime
|
| 4 |
import logging
|
| 5 |
|
|
|
|
| 6 |
logging.basicConfig(
|
| 7 |
level=logging.INFO,
|
| 8 |
format='%(asctime)s - %(message)s',
|
| 9 |
handlers=[
|
| 10 |
+
logging.StreamHandler(),
|
| 11 |
+
logging.FileHandler('/tmp/ip_log.txt')
|
| 12 |
]
|
| 13 |
)
|
| 14 |
|
| 15 |
def get_ip():
|
| 16 |
try:
|
| 17 |
+
# 使用 curl 直接访问实际的 IP 地址
|
| 18 |
+
cmd = "curl -s http://eth0.me" # 或者使用 curl -s ifconfig.me
|
| 19 |
+
result = subprocess.check_output(cmd, shell=True).decode('utf-8').strip()
|
| 20 |
+
return result
|
| 21 |
+
except Exception as e:
|
| 22 |
+
return f"错误: {str(e)}"
|
| 23 |
+
|
| 24 |
+
def get_network_info():
|
| 25 |
+
try:
|
| 26 |
+
# 获取更详细的网络信息
|
| 27 |
+
cmd = "ip addr show"
|
| 28 |
+
result = subprocess.check_output(cmd, shell=True).decode('utf-8')
|
| 29 |
+
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
except Exception as e:
|
| 31 |
return f"错误: {str(e)}"
|
| 32 |
|
|
|
|
| 35 |
|
| 36 |
while True:
|
| 37 |
ip = get_ip()
|
| 38 |
+
logging.info(f"公网IP: {ip}")
|
| 39 |
+
|
| 40 |
+
# 每小时记录一次详细的网络信息
|
| 41 |
+
if datetime.now().minute == 0:
|
| 42 |
+
network_info = get_network_info()
|
| 43 |
+
logging.info(f"网络详情:\n{network_info}")
|
| 44 |
|
|
|
|
| 45 |
time.sleep(60)
|
| 46 |
|
| 47 |
if __name__ == "__main__":
|