Python使用淘宝API查询IP归属地功能分享

2019-09-23 09:34:40王冬梅

网上有很多方法能够过去到IP地址归属地的脚本,但是我发现淘宝IP地址库的信息更详细些,所以用shell写个脚本来处理日常工作中一些IP地址分析工作。

脚本首先是从http://ip.taobao.com/的数据接口获取IP地址的JSON格式的数据信息,在使用一个python脚本来把Unicode字符转换成UTF-8编码。

Shell脚本内容:


#!/bin/bash

ipInfo() {
  for i in `cat list`
  do
    TransCoding="/usr/bin/python TransCoding.py"
    JsonDate="curl -s http://ip.taobao.com/service/getIpInfo.php?ip=$i"
    country=`$JsonDate | sed 's/,/n/g' | $TransCoding | tr -d "{}"" | awk -F ":" 'NR==2{print $3}'
    area=`$JsonDate | sed 's/,/n/g' | $TransCoding | tr -d "{}"" | awk -F ":" 'NR==4{print $2}'
    region=`$JsonDate | sed 's/,/n/g' | $TransCoding | tr -d "{}"" | awk -F ":" 'NR==6{print $2}'
    city=`$JsonDate | sed 's/,/n/g' | $TransCoding | tr -d "{}"" | awk -F ":" 'NR==8{print $2}'
    county=`$JsonDate | sed 's/,/n/g' | $TransCoding | tr -d "{}"" | awk -F ":" 'NR==10{print $2}'
    isp=`$JsonDate | sed 's/,/n/g' | $TransCoding | tr -d "{}"" | awk -F ":" 'NR==12{print $2}'
    printf "%-18st%-8st%-8st%-8st%-8st%-8st%-8sn" $i $country $isp $area $region $city $county
  done
}

printf "%-18st%-8st%-8st%-8st%-8st%-8st%-8sn" IP地址 国家 运营商 区域 省份 城市 县/区
echo -e "e[1;33m======================================================================e[0m"
ipInfo;

Python脚本内容:


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import sys

def main():
    for line in sys.stdin:
        sys.stdout.write(re.sub(r'uw{4}',
            lambda e: unichr(int(e.group(0)[2:], 16)).encode('utf-8'),
            line))

if __name__ == '__main__':
    main()

将两个脚本放在一个目录下,再将需要分析的IP地址一行一个写入在list文件中,执行 shell脚本即可。

实例演示(分析最近暴力破解服务器密码的IP归属地):

cat /var/log/secure | awk '/Failed/ {print $(NF-3)}' | sort -u > list
[root@MyVPS4407 ip]# ./ip.sh
IP地址                  国家    运营商  区域    省份    城市    县/区
======================================================================
114.112.69.50           中国    华南    广东省