bobocup commited on
Commit
bcb86dc
·
verified ·
1 Parent(s): 6fba58f

Update monitor_ip.py

Browse files
Files changed (1) hide show
  1. monitor_ip.py +22 -24
monitor_ip.py CHANGED
@@ -1,38 +1,32 @@
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
 
@@ -41,9 +35,13 @@ def main():
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__":
 
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__":