Python obtains the Ip address attribution and other information, and python obtains the ip address attribution.

Source: Internet
Author: User

Python obtains the Ip address attribution and other information, and python obtains the ip address attribution.

If you have a batch of IP addresses that want to obtain the specific information of these IP addresses, such as the country of ownership and city, the best way is to call the existing api interface to obtain the information, I wrote an article about how my blog was attacked by an unknown number of IP addresses. It was important to restore services during the attack, the attacker's IP address information after the attack can analyze the sources and features of the attack to help prompt the security of the website, today, this script obtains the specific information of the IP address based on the provided IP address. The script is as follows:

#!/usr/bin/env python import requestsimport 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)

The script explains that two functions are defined. The getIp () function reads IP information from the file and returns a list. The get_geolocation () function obtains the information and returns a dictionary, then, open a writable csv file in the main function, write the information obtained through the loop into a CSV file, and use csv when writing the csv file. the DictWriter dictionary writing function is more practical. You can directly write data with the data structure type as dictionary to a csv file, in other words, you only need to convert the data you want to write into a dictionary, so that you can easily write the data, such as my dict (zip (fieldnames, fieldnames )) this is actually the function. You can practice it yourself when using csv files.

The last part is the code of a netizen.

#! /Usr/bin/env python #-*-coding: UTF-8-*-# search for IP address locations # writer by keery_log # Create time: 2013-10-30 # Last update: 2013-10-30 # usage: python chk_ip.py www.google.com | python chk_ip.py 8.8.8.8 | python chk_ip.py ip.txt import signalimport urllibimport jsonimport sys, OS, reimport socket if len (sys. argv) <= 1: print "Please input ip address! "Sys. exit (0) def handler (signum, frame): sys. exit (0) signal. signal (signal. SIGINT, handler) url =" http://ip.taobao.com/service/getIpInfo.php? Ip = "# Find ip address def ip_location (ip): data = urllib. urlopen (url + ip ). read () datadict = json. loads (data) for oneinfo in datadict: if "code" = oneinfo: if datadict [oneinfo] = 0: return datadict ["data"] ["country"] + datadict ["data"] ["region"] + datadict ["data"] ["city"] + datadict [" data "] [" isp "] # define the IP address and domain name regular re_ipaddress = re. compile (R' ^ (25 [0-5] | 2 [0-4] [0-9] | [01]? [0-9] [0-9]?) \.) {3} (25 [0-5] | 2 [0-4] [0-9] | [01]? [0-9] [0-9]?) $ ') Re_domain = re. compile (R' [a-zA-Z0-9] [-a-zA-Z0-9] {} (\. [a-zA-Z0-9] [-a-zA-Z0-9] {}) + \.? ') If OS. path. isfile (sys. argv [1]): # If the parameter is a file, search for file_path = sys iteratively. argv [1] fh = open (file_path, 'R') for line in fh. readlines (): if re_ipaddress.match (line): city_address = ip_location (line) print line. strip () + ":" + city_addresselse: ip_address = sys. argv [1] if re_ipaddress.match (ip_address): # if the parameter is a single IP address city_address = ip_location (ip_address) print ip_address + ":" + city_address elif (re_domain.match (ip_address )): # If the parameter is domain name result = socket. getaddrinfo (ip_address, None) ip_address = result [0] [4] [0] city_address = ip_location (ip_address) print ip_address.strip () + ":" + city_address

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.