写这个脚本是因为之前发现网站有很多国外ip访问(其实是被人扫后台了🥲),所以想通过脚本来看看这些ip都是哪些国家的
ip_address.sh

  • 01
  • 02
  • 03
  • 04
  • 05
#!/bin/bash awk -F ' ' '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -n 10 | awk '{print $2}' > /tmp/top_ips.txt # 首先截取过滤ip保存到文件中 python3 ip_location.py

ip_location.py
这里需要先安装ipwhois这个库

  • 01
pip3 install ipwhois
  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
from ipwhois import IPWhois # 读取 IP 地址列表文件 with open("/tmp/top_ips.txt", "r") as f: ip_list = [line.strip() for line in f] # 查询每个 IP 地址的归属地 for ip_str in ip_list: try: # 查询 IP 地址的 WHOIS 信息 ipwhois = IPWhois(ip_str) result = ipwhois.lookup_rdap(depth=1) # 输出 IP 地址的归属地 if "asn_description" in result: print("{}: {}".format(ip_str, result["asn_description"])) elif "asn" in result: print("{}: AS{}".format(ip_str, result["asn"])) else: print("{}: Unknown".format(ip_str)) except Exception: print("{}: 获取数据失败".format(ip_str))

执行结果

  • 01
  • 02
  • 03
  • 04
  • 05
  • 06
  • 07
  • 08
  • 09
  • 10
$ ./ip_address.sh 202.146.130.230: JASNET-AS-ID PT. JASNITA TELEKOMINDO, ID 39.107.59.89: ALIBABA-CN-NET Hangzhou Alibaba Advertising Co.,Ltd., CN 125.124.72.162: CT-HANGZHOU-IDC No.288,Fu-chun Road, CN 66.249.79.233: GOOGLE, US 161.35.124.133: DIGITALOCEAN-ASN, US 193.32.162.159: UNMANAGED-DEDICATED-SERVERS, GB 128.199.68.243: DIGITALOCEAN-ASN, US 47.92.29.136: ALIBABA-CN-NET Hangzhou Alibaba Advertising Co.,Ltd., CN 66.249.79.231: GOOGLE, US