python腳本查詢(xún)外網(wǎng)IP
使用python腳本獲取外網(wǎng)IP,不用再手動(dòng)去訪問(wèn)網(wǎng)站查詢(xún)。下面是學(xué)習(xí)啦小編收集整理的python腳本查詢(xún)外網(wǎng)IP,希望對(duì)大家有幫助~~
python腳本查詢(xún)外網(wǎng)IP
工具/原料
python2.7
方法/步驟
首先安裝python2.7。
python官網(wǎng):http://python.org
打開(kāi)記事本或者其他文本編輯,例如notepad++
寫(xiě)入下面內(nèi)容:
#!/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"獲取外網(wǎng)IP地址位置失敗。".encode(PFENCODE)
print str(e)
print u"外網(wǎng)IP:".encode(PFENCODE) + str(w_ip)
print u"地理位置:".encode(PFENCODE) + data
if __name__ == "__main__":
print "\n\n" print "------------------------------------------------------"
print u"獲取外網(wǎng)IP及信息!!!!".encode(PFENCODE)
print "------------------------------------------------------"
getIP()
print "\n\n\n"
if os.name == 'nt':
os.system('pause')
else:
raw_input(u"回車(chē)退出。。。。。。。。。".encode(PFENCODE))
此腳本同樣適合Linux下使用。但是要注意格式,在windows編輯后,在Linux要運(yùn)行之前要使用vim進(jìn)行編輯,在vim命令模式下:set ff=unix 設(shè)置文件的格式,賦予執(zhí)行位就可以執(zhí)行了
運(yùn)行效果如下圖:
局域網(wǎng)python腳本查詢(xún)外網(wǎng)IP相關(guān)文章:
1.局域網(wǎng)Python中使用POST方式上傳文件