import os
import json
import http.client
import codecs
LogFile='/mnt/log/meiyiren.log'
#日志
logMess='/tmp/acc.log'
if os.path.isfile(logMess):
os.system('cp /dev/null %s'% logMess)
file=codecs.open(logMess,'w+',encoding='utf-8')
def cmd(cmd):
return os.popen(cmd).readlines()
'''
def getIp(ip):
return json.loads(os.popen("/usr/bin/curl http://ip.taobao.com/service/getIpInfo.php?ip=%s" % ip).readline())['data']
'''
conn = http.client.HTTPConnection('ip.taobao.com')
def getIpCountry(ip):
conn.request('GET','/service/getIpInfo.php?ip=%s' % ip)
r1=conn.getresponse()
if r1.status == 200:
return json.loads(r1.read())['data']
else:
return "Error"
#將access.log文件進行分析,並轉為python數組
file.write(u"字段說明:ip 訪問次數據 ip國家 城市的 isp號 省份 所在地區\n")
ipDb=[]
for i in cmd('''/usr/bin/awk '{print $1}' %s |sort |uniq -c''' % LogFile):
ip = i.strip().split(' ')
ipDb.append(ip)
#通過taobao 提供接口分析ip地址來源
for i in ipDb:
_tmpD=getIpCountry(i[1])
#格式說明:ip 訪問次數據 ip國家 城市的 isp號 省份 所在地區
out="%s%s%s%s%s%s%s"%(i[1].ljust(20),i[0].ljust(10),_tmpD['country'].ljust(20),_tmpD['city'].ljust(16),_tmpD['isp_id'].ljust(16),_tmpD['region'].ljust(16),_tmpD['area'].ljust(16))
print (out)
file.write("%s\n"%out)
conn.close()
file.close()
錯誤提示
Traceback (most recent call last):
File "/opt/test.py", line 33, in
tmpD=getIpCountry(i[1])
File "/opt/test.py", line 22, in getIpCountry
return json.loads(r1.read())['data']
File "/usr/local/python3.4/lib/python3.4/json/_init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
你讀取的數據是byte數組,需要先轉換成str字符串