脚本统计ip的海外用户分布情况或者国内省份的分布情况
2017-11-20 20:20
465 查看
背景:日志文件会产生ip字段,现需要统计ip的分布情况
前提:必须有这么一个服务,输入指定的ip能返回相应的地理位置的信息。可以直接调用。
思想:首先提取出ip字段,一般用sed命令或者和cut结合。
例如,日志格式如下:
[INFO][2017-11-18 00:00:00] reqhandler.py 134, allocate, hid:XXXX msg:{'province': 'sn', 'ccid': -1, 'ip': 'xxx.xxx.xxx.xxx', 'isp': 'unicom', 'mid': 0, 'spaceid': '5A10BA4FCBB011E7A162000E1EFF0BA0', 'locator': 8, 'game': 10038, 'eid': 148079890, '_cmd_': 327681}可以用以下命令来提取ip字段。
grep "allocate," /home/XX/logs/*/XX.2017-11-17 | sed "s/^.* 'ip': '//g" | sed "s/', 'isp'.*//g" >> /home/XX/ip_1117.log
然后再用脚本去统计分布情况。(ip.mmdb 为一个ip映射的文件,此脚本用于统计国内省份分布情况)
# coding: utf8 import maxminddb import csv def get_country(): reader = maxminddb.Reader('/home/XX/ip_log/ip.mmdb') en2zw = {} en2count = {} ips = get_record_from_file('/home/XX/ip_log/test.log') total_len = len(ips) / 1000 count = 0 for ip in ips: count += 1 try: result = reader.get(ip) print result except Exception as ex: print ip, ex continue if not result: print ip, result continue zw = result['subdivisions']['names'].get('zh_CN', '') en = result['subdivisions']['names'].get('en', '') ct = result['country']['names'].get('en', '') print zw, en, ct if ct != 'China': continue if en not in en2zw: en2zw[en] = zw if en not in en2count: en2count[en] = 1 else: en2count[en] += 1 print '统计结果' print en2count en2count.pop('China', None) total = sum(en2count.values()) * 1.0 print 'total:', total for en, count in en2count.iteritems(): print 'en:%s, zh_CN: %s, count:%s percent:%s' % (en, en2zw.get(en), count, count / total)
def get_record_from_file(filename): u""" 从文件中读取内容并放回,不适合操作大文件 Args: filename {str} 文档的路径 """ ret = [] with open(filename) as f: for record in f: record = record.strip() if not record: continue ret.append(record) return ret if __name__ == '__main__': get_country()
相关文章推荐
- 统计中心机房与各地域ip(连接)分布情况
- 统计 DHCP 服务器 ip 分配情况的脚本
- 统计 DHCP 服务器 ip 分配情况的脚本
- Oracle EBS用户登录情况统计脚本
- 简单统计SQLSERVER用户数据表大小(包括记录总数和空间占用情况)转
- 一个查看全部用户的磁盘空间使用情况的脚本
- 最简单的统计appche站点IP访问量的shell脚本
- php 封装函数 多种情况下 自动获取用户ip
- shell 脚本查看网段ip使用情况
- crontab 中的指定特定的用户身份来运行相关的命令或者脚本
- 【Shell】建立一个脚本统计当前登录用户数
- asterisk 用户对接获取外网IP 脚本
- 用shell脚本实现增加,删除用户,查询更改UID和GID以及统计用户数
- 一个查看所有用户的磁盘空间使用情况的脚本
- oracle 10G 在windows下有网络情况下安装 断网或者换ip不能使用(报无监听程序或者,监听程序无法解析链接
- nginx在使用varnish作缓存情况下获取用户真实ip
- 统计CDN的尝试下载IP数和下载成功IP数做的一个CDN统计脚本
- 普通用户利用脚本及runas自动更改IP(无需输入密码)
- 普通用户利用脚本及runas自动更改IP
- 一个统计当前网段活动IP数量的脚本