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

Update monitor_ip.py

Browse files
Files changed (1) hide show
  1. 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
- # 尝试多个 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
 
@@ -40,8 +42,10 @@ 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)
 
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)