python3 分析linux 异常IP登录记录

前言

  前几天注意到服务器出现了很多异常IP登录信息,抽空写了个脚本,分享给大家。 小白初学python,如有问题敬请指出,谢谢。 测试过几个查询IP的API 就cip.cc比较稳定。但个人访问速度有限制,所以查询较慢。

使用方法

  启动时需要带参数
  如 ./ip_query.py lastb 可使用如下几个参数

last
lastb
last -f /var/log/btmp…
last -f /var/log/wtmp…

程序默认将输出文件保存在/root/log目录下,必要下请先修改程序输出路径

效果

查询登录信息

./ip_query.py last
在这里插入图片描述

查询异常登录信息

./ip_query.py lastb
在这里插入图片描述

程序

#!/usr/bin/env python3

import os,json,time,sys,requests

runtime = time.time()

ip_all = []
ip_sou = []
test_num = []
date = ""

month = ['Jan','Feb','Mar','Apr','May','Jun','Aug','Sept','Oct','Nov','Dec']

if len(sys.argv) == 1 :
    cmd = 'last'
else:
    cmd = sys.argv
    del cmd[0]
    cmd = ' '.join(cmd)

#print(cmd)

f1 = os.popen(cmd)
f2 = f1.readlines()

for i in f2:
    if 'reboot' not in i:
        if 'begins' not in i:
            i = i.split()
            if len(i) > 0 :
                if 'pts' in i[1] or ':' in i[1]:
                    if ':pts/' not in i[2]:
                        ip_all.append(i[2])
                else:
                    ip_all.append(i[1])
        else:
            date = i

for i in ip_all:
    if i not in ip_sou:
        ip_sou.append(i)
        test_num.append(ip_all.count(i))  

a = 0
b = len(ip_sou)
datelist = date.split()

startdate = ('%s-%d-%s_%s'%(datelist[6],month.index(datelist[3])+1,datelist[4],datelist[5]))
timeflog = int(time.strftime("%m", time.localtime()))

if timeflog > month.index(datelist[3])+1:
    enddate = '--月底'
else:
    enddate = time.strftime("--%m-%d", time.localtime())

if 'wtmp' in datelist[0]:
    filename = '/root/log/login_'+startdate+enddate        #修改文件输出位置及文件名。
    buf = "源IP数量:%d     登录次数:%d次 "%(b,len(ip_all))
elif 'btmp' in datelist[0]: 
    filename = '/root/log/nologin_'+startdate+enddate      #同意文件输出位置及文件名
    buf = "源IP数量:%d     总攻击人次:%d次 "%(b,len(ip_all))
else:
    print(date)

filename = filename + '_%d次'%len(ip_all)
#filename = 'ceshi_ip' 
print(filename)
out = open(filename,'w')

print(date)
print(buf)
out.write(date)
out.write(buf+'\n')

while a<b:
#    data = ip_info(ip_sou[a])
    f1 = os.popen('curl -s http://www.cip.cc/%s'%ip_sou[a])
    f2 = f1.readlines()
    for i in range(f2.count('\n')):
        f2.remove('\n')
    f2 = ''.join(f2)
    f2 = f2.rstrip('\n').replace('\t','').replace(": ",'":"').replace('\n','","').replace('  ',' ')
    f2 = '{"'+f2+'"}'
    if 'Operation too frequent' in f2:
        continue
    if 'IP' in f2:
        data = json.loads(f2)
    else:
        print('出错%s'%f2)
        print(ip_sou[a])
        time.sleep(3)
        continue
    if 'btmp' in datelist[0]:
        le = (len(data['地址'])-data['地址'].count(' '))*2+data['地址'].count(' ')
        text = data['地址']+' '*(25-le)
        buf = '%-15s  攻击%3d次 地址:%s'%(ip_sou[a],test_num[a],text)
        if '运营商' in data:
            buf = buf + ' 运营商:%-20s'%data['运营商'] 
        if '数据二' in data:
            text = data['数据二'].replace(' ','')
            buf = buf+' 备注:%s'%text
        if '数据三' in data:
            text = data['数据三'].replace(' ','')
            buf = buf+' %s'%text
    else:
        le = (len(data['地址'])-data['地址'].count(' '))*2+data['地址'].count(' ')
        text = data['地址']+' '*(25-le)
        buf = '%-15s  登录%3d次  地址:%s'%(ip_sou[a],test_num[a],text)
        if '运营商' in data:
            buf = buf + ' 运营商:%-20s'%data['运营商']
        if '数据二' in data:
            text = data['数据二'].replace(' ','')
            buf = buf+' 备注:%s'%text
        if '数据三' in data:
            buf = buf+' %s'%data['数据三'] 
    print('%6.2f%% '%((a+1)*100/b) + buf)
    out.write(buf+'\n')
    a += 1
out.close()
endtime = time.time()
print("运行时间:%s s"%(endtime-runtime))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萌新程序猿~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值