bobocup commited on
Commit
4d0fa78
·
verified ·
1 Parent(s): 7c1c1db

Update monitor_ip.py

Browse files
Files changed (1) hide show
  1. monitor_ip.py +19 -25
monitor_ip.py CHANGED
@@ -1,5 +1,4 @@
1
- import socket
2
- import requests
3
  import time
4
  from datetime import datetime
5
  import logging
@@ -8,33 +7,26 @@ 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,12 +34,14 @@ def main():
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)
52
 
53
  if __name__ == "__main__":
 
1
+ import subprocess
 
2
  import time
3
  from datetime import datetime
4
  import logging
 
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
 
 
34
  logging.info("IP 监控已启动")
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__":