蘭雅sRGB 个人笔记 https://262235.xyz
提供编程和电脑应用视频教程,工具和源代码
C, C++, Python Programming, Source Code, Video

旧Hexo博客 | Github | IP定位WebAPI | Docker Hub
编程中文文档 | 网盘分享 | 中文Linux命令

Python脚本和Bash命令统计访问爬虫的IP地址和城市信息

ipinfo.png

首先部署 IP地址信息库,参考 https://github.com/hongwenjun/ip

统计日志中IP排名写到iplist.txt,批量查IP地址信息,最新日志100条

  • 参考如下 Bash 命令,第一行中是查看 一个容器的日志
  • 如果不是 Docker 环境部署 Nginx,日志文件是 /var/log/nginx/access.log
docker logs nginx-php 2>/dev/null \
  | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' \
  | sort | uniq -c| sort -nrk 1 | head -n 100 | tee iplist.txt

使用 python3 ipinfo.py 命令读取 iplist.txt 输出 IP地址和城市

# ipinfo.py
import re, ipdb, ipaddress
db = ipdb.BaseStation("/app/qqwry.ipdb")
with open("/app/iplist.txt", "r") as f:
    data = f.read()

iplist = re.findall(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b", data)
for ip in iplist:
   try:
      ipaddress.ip_address(ip).is_global
      city = db.find(ip, "CN")
      print(ip + " @" + city[0] + city[1] + city[2] + city[3])
   except:
      pass

# 统计日志中IP排名写到iplist.txt,批量查IP地址信息,最新日志100条
"""
docker logs nginx-php 2>/dev/null \
  | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' \
  | sort | uniq -c| sort -nrk 1 | head -n 100 | tee iplist.txt

docker exec -it python3 python3 ipinfo.py

docker logs nginx-php 2>/dev/null | tail -100  \
  | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' \
  | sort | uniq -c| sort -nrk 1 | head -n 100 | tee iplist.txt
"""

我的环境都是Docker部署的,所以使用脚本注释中的 命令行就可以很方获得信息。

  • 如果你的环境不同,请修改对应文件的实际目录
  • 实际使用效果,两个命令查询最新访问服务器的iP
    ip.png
本原创文章自由转载,转载请注明本博来源及网址 | 当前页面:蘭雅sRGB 个人笔记 » Python脚本和Bash命令统计访问爬虫的IP地址和城市信息