您的当前位置:首页正文

python获取ip归属信息

2024-08-01 来源:伴沃教育

今天给大家分享的是python获取归属信息,下面是相关代码:

脚本如下:

#!/usr/bin/env python

import requests

import csv

def getIp(file):

    iplist = []

    fi = open(file, 'r')

    for ip in fi:

        ip = ip.strip()

        iplist.append(ip)

    return iplist

def get_geolocation(ip):

    r = requests.get('https://freegeoip.net/json/' + ip)

    info = [str(r.json()['country_name']), str(r.json()['city'])]

    return {'ip':ip, 'country_name':info[0], 'city_name':info[1]}

if __name__ == '__main__':

    iplist = getIp('/root/ipfile')

    f = open('outputinfo.csv', 'a+')

    fieldnames = ['ip', 'country_name', 'city_name']

    dict_writer = csv.DictWriter(f, fieldnames=fieldnames)

    dict_writer.writerow(dict(zip(fieldnames, fieldnames)))

    for ip in iplist:

        data = get_geolocation(ip)

        dict_writer.writerow(data)

以上就是关于python获取ip归属信息的全部介绍了,希望能够给大家带来帮助。

显示全文