python网站访问统计

#!/usr/local/bin/python3
# coding:utf-8

# ====================================================
# Author: chang - EMail:[email protected]
# Last modified: 2017-5-13
# Filename: accesstimes.py
# Description: real time analysis nginx log,base time, os, re, pymysql, Thread
# blog:http://www.cnblogs.com/changbo
# ====================================================

"""
需求:每隔1分钟读取nginx日志文件
notice:
模拟日志切割过程中初始化脚本参数
cp access.log access2017xxxx.log  && echo > access.log && echo ‘0‘> offset1.txt
"""

import time
import os
import re
import pymysql
from threading import Thread
import logging
# from django.db import connection

logging.basicConfig(level=logging.DEBUG,
                    format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘,
                    datefmt=‘%a, %d %b %Y %H:%M:%S‘,
                    filename=‘accesstimes.log‘,
                    filemode=‘w‘)

keypage = [‘/sys/get_user.do‘]
keyIP = [‘127.0.0.1‘, ‘119.28.61.122‘]
engdate = {‘Jan‘: ‘1‘, ‘Feb‘: ‘2‘, ‘Mar‘: ‘3‘, ‘Apr‘: ‘4‘, ‘May‘: ‘5‘, ‘Jun‘: ‘6‘, ‘Jul‘: ‘7‘, ‘Aug‘: ‘8‘, ‘Sept‘: ‘9‘,
           ‘Oct‘: ‘10‘, ‘Nov‘: ‘11‘, ‘Dec‘: ‘12‘}

def dateformat(nginxdate):
    day = (nginxdate.split(‘[‘)[1]).split(‘/‘)[0]
    month = engdate[(nginxdate.split(‘[‘)[1]).split(‘/‘)[1]]
    year = (nginxdate.split(‘[‘)[1]).split(‘/‘)[2]

    return year + ‘-‘ + month + ‘-‘ + day

# write log offset
def writeoffset(number):
    with open(‘offset1.txt‘, ‘w+‘) as f3:
        f3.write(number)
        f3.flush()

# get log offset
def getoffset():
    with open(‘offset1.txt‘) as f2:
        offset = f2.readline()
        return offset

db = pymysql.connect("xxx.xxx.xxx.xxx", "xxx", "xxxxxx", "yunwei")
cursor = db.cursor()
# cleantable = ‘TRUNCATE abnormal‘

def handleline(logline):
    susptmp = logline.split(" ")
    if len(susptmp) > 2:
        if susptmp[0] not in keyIP:
            del susptmp[1:3]
            if len(susptmp) > 2:
                ip = susptmp[0]
                time1 = (susptmp[1].split(‘:‘, 1))[1]
                dated = dateformat((susptmp[1].split(‘:‘, 1))[0])

                # print(ip + ‘---‘, time1 + ‘---‘, date + ‘---‘, user + ‘---‘, passd + ‘---‘)
                sql = "INSERT INTO reqinfo(ip, timedd, datedd) VALUES(‘%s‘, ‘%s‘, ‘%s‘)" % (ip, time1, dated)
                try:
                    cursor.execute(sql)
                    db.commit()
                    logging.debug(‘Insert success!‘)
                except Exception as e:
                    logging.debug(e)

# online analysis log
def analysislog():
    with open(‘access.log‘) as f1:
        while True:
            # get offset
            lastoffset = getoffset()
            # jump the Specify log line
            f1.seek(int(lastoffset))
            # 获取该行偏移量
            where = f1.tell()
            line = f1.readline()
            writeoffset(str(where))
            if not line:
                time.sleep(10)
                f1.seek(where)
            else:
                # 处理该行,并获取改行的偏移量且写入文件
                handleline(line)
                nowoffset = f1.tell()
                writeoffset(str(nowoffset))

if __name__ == ‘__main__‘:
    if not os.path.exists(‘offset1.txt‘):
        with open("offset1.txt", ‘w‘) as f:
            f.write(‘0‘)

    t1 = Thread(target=analysislog)
    t1.start()
#!/usr/local/bin/python3
# coding:utf-8

# ====================================================
# Author: chang - EMail:[email protected]
# Last modified: 2017-5-13
# Filename: reqcounts.py
# Description: real time analysis nginx log,pymysql, Thread, logging
# blog:http://www.cnblogs.com/changbo
# ====================================================

import pymysql
import logging
from threading import Thread

logging.basicConfig(level=logging.DEBUG,
                    format=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘,
                    datefmt=‘%a, %d %b %Y %H:%M:%S‘,
                    filename=‘reqcounts.log‘,
                    filemode=‘w‘)

db = pymysql.connect("xxx.xxxx.xxx.xxx", "xxxx", "xxxxx", "xxxxx")
cursor = db.cursor()
# cleantable = ‘TRUNCATE tablename‘

def analysisdb():
    listtime = []
    listip = []
    listdated = []

    sql3 = ‘SELECT ip, timedd, datedd FROM reqinfo‘
    cursor.execute(sql3)
    results = cursor.fetchall()
    for row in results:
        listtime.append(row[1])
        listip.append(row[0])
        listdated.append(row[2])

        try:
            # 统计1分钟内页面访问次数
            sql1 = "SELECT count(*) from reqinfo where timedd=‘%s‘ and ip=‘%s‘ and datedd=‘%s‘" % (
                listtime[0], listip[0], listdated[0])
            sql4 = "DELETE from reqinfo where timedd=‘%s‘ and ip=‘%s‘ and datedd=‘%s‘" % (
                listtime[0], listip[0], listdated[0])
            sql5 = "DELETE FROM reqcounts WHERE timesddd=0"
            cursor.execute(sql1)
            datad = cursor.fetchone()
            sql2 = "INSERT INTO reqcounts(ip, timesddd, timeddd, dateddd) VALUES(‘%s‘ , ‘%s‘ , ‘%s‘, ‘%s‘)" % (
            listip[0], datad[0], listtime[0], listdated[0])
            cursor.execute(sql2)
            db.commit()
            logging.debug(‘-----Insert success -------‘)
            # delete already insert data of requinfo
            cursor.execute(sql4)
            db.commit()
            del listtime[0]
            del listip[0]
            del listdated[0]
            cursor.execute(sql5)
            db.commit()
        except Exception as e:
            logging.debug(e)

if __name__ == ‘__main__‘:
        t2 = Thread(target=analysisdb)
        t2.start()

html 页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    {% load static %}
    <link rel="stylesheet"  type="text/css" href="{% static "css/style.css" %}" />
    <title>访问统计</title>
<script language="javascript" type="text/javascript">
window.onload = function(){
    var oTable = document.getElementById("bbsTab");
    for(var i=0;i<oTable.rows.length;i++){
        oTable.rows[i].cells[0].innerHTML = (i+1);
        if(i%2==0)    //偶数行
            oTable.rows[i].className = "ys01";
    }
}
</script>
</head>
<body>

<div id="container">
<table class="zebra">
<caption>IP/s 并发量统计</caption>
<thead>
<tr>
    <th>序号</th>
    <th>ip</th>
    <th>登录次数</th>
    <th>时间</th>
    <th>日期</th>
</tr>
</thead>
<tbody id="bbsTab">
{% for reqinfocount in reqinfocounts %}
    <tr>
    <td></td>
    <td>{{ reqinfocount.ip|safe }}</td>
    <td>{{ reqinfocount.timesddd|safe }}</td>
    <td>{{ reqinfocount.timeddd|safe }}</td>
    <td>{{ reqinfocount.dateddd|safe }}</td>
    </tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>

效果图

END!

时间: 2024-10-09 03:49:47

python网站访问统计的相关文章

开源网站访问统计系统Piwik

http://www.piwik.cn/ http://www.piwik.org/ Piwik 是一套基于 Php+MySQL 技术构建,能够与 Google Analytics 相媲美的开源网站访问统计系统.Piwik 可以给你详细的统计信息,比如网页浏览人数, 访问最多的页面, 搜索引擎关键词等等,并且采用了大量的AJAX/Flash技术,使得在操作上更加便易. Piwik 可以安装在你的服务器上面,数据就保存在你自己的服务器上 面.你可以非常容易的插入统计图表到你的博客或是网站后台的控制

给博客添加网站访问统计(第三方网站统计)

做博客,论坛等网站的站长希望了解自己网站最近的访问情况,比如访问量,浏览页面,客户端等相关数据,这些可以通过第三方网站统计实现.WEB端网站统计有CNZZ(http://www.cnzz.com/),51啦(http://www.51.la/),百度统计(http://tongji.baidu.com/)等,WAP端网站统计有沐恩统计(http://m.moonsn.com/),统计吧(http://stat8.cn/)等.博主笑忘书在此推荐本人一直在用的51啦网站统计,十二年的老站,各方面都不

ASP.NET MVC编程入门--网站访问统计

参考文章:Asp.Net MVC3.0网站统计登录认证的在线人数 参考文章:ASP.net中网站访问量统计方法代码 Global 代码: protected void Application_Start() { Application["online"] = 0; ///在应用程序第一次启动时初始化在线人数为0 AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); log4

apache配置网站访问统计awstats

1.解压缩awstas软件 2.建立配置文件 3.在屏幕最下面输入/usr/local/httpd/conf/httpd.conf y y 4.修改站点统计配置文件 修改下面的两项 建立数据目录 5.执行日志分析 6.为了及时更新和更新方便,创建计划任务 在客户机上访问日志分析系统 http://www.google.com/awstats/awstats.pl?config=www.google.com

部署Apache网站访问统计-AWStats分析系统

1.安装AWStats软件包 将软件解压到httpd服务器/usr/local/目录下 [[email protected] /]# tar zxf awstats-7.3.tar.gz

ASP.net中网站访问量统计方法代码(在线人数,本月访问,本日访问,访问流量,累计访问)

一.建立一个数据表IPStat用于存放用户信息 我在IPStat表中存放的用户信息只包括登录用户的IP(IP_Address),IP来源(IP_Src)和登录时间 (IP_DateTime),些表的信息本人只保存一天的信息,如果要统计每个月的信息则要保存一个月.因为我不太懂对数据日志的操作,所以创建此表,所 以说我笨吧,哈哈. 二.在Global.asax中获取用户信息 在Global.asax的Session_Start即新会话启用时获取有关的信息,同时在这里实现在线人数.访问总人数的增量统计

JSP:用隐式对象统计网站访问次数

JSP:用隐式对象统计网站访问次数 jsp 隐式对象 赵振江 隐式对象 application对象 利用隐式对象为某一网站编写一个JSP程序,统计该网站的访问次数. 一种情况是:按照客户进行统计(按照浏览器进行统计,一个浏览器如果访问网站的话,就算一次访问,换句话说如果这个浏览器刷新多次网站的话,也算是一次访问): 另一种情况:刷新一次页面,就算是一次访问. 要求用隐式对象去实现. counter.jsp <%@ page language="java" import="

统计网站访问人数

添加一个Global.asax文件,加入以下代码: void Application_Start(object sender, EventArgs e) { // 在应用程序启动时运行的代码 int count = 0; System.IO.StreamReader srd; string file_path = Server.MapPath("counter.txt"); //打开文件进行读取 srd = System.IO.File.OpenText(file_path); whi

Servlet学习的两个案例之网站访问次数的统计

一.统计次数的Servlet源码 package com.shanrengo; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.