Python查询IP地址归属完整代码

yipeiwu_com6年前Python基础

本文实例为大家分享了Python查询IP地址归属的具体代码,供大家参考,具体内容如下

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#查找IP地址归属地
#writer by keery_log
#Create time:2013-10-30
#Last update:2013-10-30
#用法: python chk_ip.py www.google.com |python chk_ip.py 8.8.8.8 |python chk_ip.py ip.txt
 
import signal
import urllib
import json
import sys,os,re
import 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="
 
#查找IP地址
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"]
 
#定义IP与域名正则
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]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?')
 
if os.path.isfile(sys.argv[1]): #如果参数是文件,迭代查找
  file_path = sys.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_address
else:
  ip_address = sys.argv[1]
  if re_ipaddress.match(ip_address): #如果参数是单个IP地址
    city_address = ip_location(ip_address)
    print ip_address + ":" + city_address
  elif(re_domain.match(ip_address)): #如果参数是域名
    result = socket.getaddrinfo(ip_address, None)
    ip_address = result[0][4][0]
    city_address = ip_location(ip_address)
    print ip_address.strip() + ":" + city_address

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python类中方法getitem和getattr详解

1、getitem 方法 使用这个方法最大的印象就是调用对象的属性可以像字典取值一样使用中括号['key'] 使用中括号对对象中的属性进行取值、赋值或者删除时,会自动触发对应的__g...

ActiveMQ:使用Python访问ActiveMQ的方法

ActiveMQ:使用Python访问ActiveMQ的方法

Windows 10家庭中文版,Python 3.6.4,stomp.py 4.1.21 ActiveMQ支持Python访问,提供了基于STOMP协议(端口为61613)的库。 Act...

python中Pycharm 输出中文或打印中文乱码现象的解决办法

python中Pycharm 输出中文或打印中文乱码现象的解决办法

1. 确保文件开头加上以下代码: # -*- coding:utf-8 -*- 还可以加上 import sys reload(sys) sys.setdefaulte...

分数霸榜! python助你微信跳一跳拿高分

前言 最近微信的跳一跳很火,大家看到排行榜上几百上千的分数,再看看自己百分左右的分数肯定很难过,我手残怪我吗?没关系,如果你跟着我来,也能让你分数霸榜。 原理 首先大家是有一个直观感受,...

python3访问sina首页中文的处理方法

复制代码 代码如下:"""如果只用普通的import urllib.requesthtml = urllib.request.urlopen("http://www.sina.com")...