Python中怎么分析网站日志数据
发表于:2025-02-04 作者:千家信息网编辑
千家信息网最后更新 2025年02月04日,Python中怎么分析网站日志数据,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。数据来源import numpy as npimpo
千家信息网最后更新 2025年02月04日Python中怎么分析网站日志数据数据来源
Python中怎么分析网站日志数据,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
数据来源
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport apache_log_parser # 首先通过 pip install apache_log_parser 安装库%matplotlib inline
fformat = '%V %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %T' # 创建解析器p = apache_log_parser.make_parser(fformat)
sample_string = 'koldunov.net 85.26.235.202 - - [16/Mar/2013:00:19:43 +0400] "GET /?p=364 HTTP/1.0" 200 65237 "http://koldunov.net/?p=364" "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11" 0'data = p(sample_string) #解析后的数据为字典结构data
datas = open(r'H:\python数据分析\数据\apache_access_log').readlines() #逐行读取log数据log_list = [] # 逐行读取并解析为字典for line in datas:data = p(line)data['time_received'] = data['time_received'][1:12]+' '+data['time_received'][13:21]+' '+data['time_received'][22:27] #时间数据整理log_list.append(data) #传入列表
log = pd.DataFrame(log_list) #构造DataFramelog = log[['status','response_bytes_clf','remote_host','request_first_line','time_received']] #提取感兴趣的字段log.head()#status 状态码 response_bytes_clf 返回的字节数(流量)remote_host 远端主机IP地址 request_first_line 请求内容t ime_received 时间数据
log['time_received'] = pd.to_datetime(log['time_received']) #把time_received字段转换为时间数据类型,并设置为索引log = log.set_index('time_received')log.head()
log['status'] = log['status'].astype('int') # 转换为int类型
log['response_bytes_clf'].unique()array(['26126', '10532', '1853', ..., '66386', '47413', '48212'], dtype=object)
log[log['response_bytes_clf'] == '-'].head() #对response_bytes_clf字段进行转换时报错,查找原因发现其中含有"-"
def dash3nan(x): # 定义转换函数,当为"-"字符时,将其替换为空格,并将字节数据转化为M数据 if x == '-':x = np.nan else:x = float(x)/1048576 return x
log['response_bytes_clf'] = log['response_bytes_clf'].map(dash3nan)log.head()
log.dtypes
流量起伏不大,但有一个极大的峰值超过了20MB。
log[log['response_bytes_clf']>20] #查看流量峰值
t_log = log['response_bytes_clf'].resample('30t').count()t_log.plot()
对时间重采样(30min),并计数 ,可看出每个时间段访问的次数,早上8点访问次数最多,其余时间处于上下波动中。
h_log = log['response_bytes_clf'].resample('H').count()h_log.plot()
当继续转换频率到低频率时,上下波动不明显。
d_log = pd.DataFrame({'count':log['response_bytes_clf'].resample('10t').count(),'sum':log['response_bytes_clf'].resample('10t').sum()}) d_log.head()
构造访问次数和访问流量的 DataFrame。
plt.figure(figsize=(10,6)) #设置图表大小ax1 = plt.subplot(111) #一个subplotax2 = ax1.twinx() #公用x轴ax1.plot(d_log['count'],color='r',label='count')ax1.legend(loc=2)ax2.plot(d_log['sum'],label='sum')ax2.legend(loc=0)
绘制折线图,有图可看出,访问次数与访问流量存在相关性。
IP地址分析
ip_count = log['remote_host'].value_counts()[0:10] #对remote_host计数,并取前10位ip_count
ip_count.plot(kind='barh') #IP前十位柱状图
import pygeoip # pip install pygeoip 安装库# 同时需要在网站上(http://dev.maxmind.com/geoip/legacy/geolite)下载DAT文件才能解析IP地址gi = pygeoip.GeoIP(r'H:\python数据分析\数据\GeoLiteCity.dat', pygeoip.MEMORY_CACHE)info = gi.record_by_addr('64.233.161.99')info #解析IP地址
ips = log.groupby('remote_host')['status'].agg(['count']) # 对IP地址分组统计ips.head()
ips.drop('91.224.246.183',inplace=True)ips['country'] = [gi.record_by_addr(i)['country_code3'] for i in ips.index] # 将IP解析的国家和经纬度写入DataFrameips['latitude'] = [gi.record_by_addr(i)['latitude'] for i in ips.index]ips['longitude'] = [gi.record_by_addr(i)['longitude'] for i in ips.index]ips.head()
country = ips.groupby('country')['count'].sum() #对country字段分组统计country = country.sort_values(ascending=False)[0:10] # 筛选出前10位的国家country
country.plot(kind='bar')
俄罗斯的访问量最多,可推断该网站来源于俄罗斯。
from mpl_toolkits.basemap import Basemapplt.style.use('ggplot')plt.figure(figsize=(10,6))map1 = Basemap(projection='robin', lat_0=39.9, lon_0=116.3,resolution = 'l', area_thresh = 1000.0)map1.drawcoastlines()map1.drawcountries()map1.drawmapboundary()map1.drawmeridians(np.arange(0, 360, 30))map1.drawparallels(np.arange(-90, 90, 30))size = 0.03for lon, lat, mag in zip(list(ips['longitude']), list(ips['latitude']), list(ips['count'])):x,y = map1(lon, lat)msize = mag * sizemap1.plot(x, y, 'ro', markersize=msize)
关于Python中怎么分析网站日志数据问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。
数据
分析
地址
时间
流量
网站
字段
次数
问题
日志
上下
内容
国家
字典
字节
峰值
数据分析
更多
来源
类型
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
两个数据库使用一个虚拟地址
神武手游跨平台服务器
sql数据库数据类型
http 服务器配置网站
工业实时数据库的意义
阿里巴巴软件开发是哪个部门
数据库闭包计算器
鸿蒙万物互联网络安全
网络技术在铁路上的应用
网络安全党支部委员责任分工
网络服务器为什么当中的灯会暗掉
厄运之锤是什么服务器
学校存在的网络安全问题
维护服务器要做什么
财务软件开发
ns看服务器
2020关于数据库安全现状
3dmax服务器激活
平顶山租房软件开发
大型网络技术架构pdf
秘乐软件开发
怎么统计多个表格数据库
geo数据库课程
网络技术部是什么
云开发数据库获取数组
页面连接数据库升级
数据库所有修改字段内容
我不是黑客我是网络技术科研人员
红人装自己做数据库
双代号网络技术et