python3 分析linux 異常IP登錄記錄

前幾天注意到服務器出現了很多異常IP登錄信息,抽空寫了個腳本,分享給大家。
小白初學python,如有問題敬請指出,謝謝。
測試過幾個查詢IP的API 就cip.cc比較穩定。但個人訪問速度有限制,所以查詢較慢。

使用方法

啓動時需要帶參數 如 ./ip_query.py lastb
可使用如下幾個參數
1、last
2、lastb
3、last -f /var/log/btmp…
4、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))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章