python脚本查询外网IP
使用python脚本获取外网IP,不用再手动去访问网站查询。下面是学习啦小编收集整理的python脚本查询外网IP,希望对大家有帮助~~
python脚本查询外网IP
工具/原料
python2.7
方法/步骤
首先安装python2.7。
python官网:http://python.org
打开记事本或者其他文本编辑,例如notepad++
写入下面内容:
#!/usr/bin/env python2
# -*- coding:GBK -*-
import urllib2,json
import re
import os
if os.name == 'nt':
PFENCODE = 'GBK'
else:
PFENCODE = 'utf-8'
def getIP():
ipinfo = "" w_ip = ""
try:
ipinfo = urllib2.urlopen('http://www.whereismyip.com').read()
w_ip = re.search('\d+\.\d+\.\d+\.\d+',ipinfo).group(0)
except:
try:
ipinfo = urllib2.urlopen('http://ip138.com/ip2city.asp').read()
w_ip = re.search('\d+\.\d+\.\d+\.\d+',ipinfo).group(0)
except Exception ,e:
print str(e)
try:
kk = urllib2.urlopen('http://ip.taobao.com/service/getIpInfo.php?ip=%s'%str(w_ip)).read()
kk_dict = json.loads(kk)[u'data']
data = kk_dict[u'country'].encode(PFENCODE)
data = data + " " + kk_dict[u'region'].encode(PFENCODE)
data = data + " " + kk_dict[u'city'].encode(PFENCODE)
data = data + " " + kk_dict[u'county'].encode(PFENCODE)
data = data + " " + kk_dict[u'isp'].encode(PFENCODE)
except Exception ,e:
print u"获取外网IP地址位置失败。".encode(PFENCODE)
print str(e)
print u"外网IP:".encode(PFENCODE) + str(w_ip)
print u"地理位置:".encode(PFENCODE) + data
if __name__ == "__main__":
print "\n\n" print "------------------------------------------------------"
print u"获取外网IP及信息!!!!".encode(PFENCODE)
print "------------------------------------------------------"
getIP()
print "\n\n\n"
if os.name == 'nt':
os.system('pause')
else:
raw_input(u"回车退出。。。。。。。。。".encode(PFENCODE))
此脚本同样适合Linux下使用。但是要注意格式,在windows编辑后,在Linux要运行之前要使用vim进行编辑,在vim命令模式下:set ff=unix 设置文件的格式,赋予执行位就可以执行了
运行效果如下图:
局域网python脚本查询外网IP相关文章: