问题描述
- python分析apache日志,大家看看错在哪
-
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("%sn"%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字符串
解决方案二:
return json.loads(r1.read().decode())['data']
时间: 2024-10-26 05:44:19