import re
import datetime
import netmiko
import calendar
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
############trên switch cần gõ các lệnh này trước##########
#login on-success log every 1
##########################################################
#################SEND MAIL FUNCTION###############
def sendMail(output,dstMail):
if(output!=''):
msg = MIMEMultipart()
msg['From'] = 'haiedubit@outlook.com'
msg['To'] = dstMail
msg['Subject'] = "WARNING CÓ NGƯỜI LOGIN THIẾT BỊ"
msg.attach(MIMEText(output, 'plain'))
text=msg.as_string()
s = smtplib.SMTP(host='smtp-mail.outlook.com')
s.starttls()
s.login('haiedubit@outlook.com', 'edubit@bnn')
s.sendmail(
"haiedubit@outlook.com",dstMail,text)
s.quit()
#######################################
sw1 = {
'device_type': 'cisco_ios',
'ip': '10.1.2.3',
'username': 'monitor',
'password': 'abc@123',
'secret': 'abc@123',
'verbose': False,
}
ip_of_ubuntu = '10.64.1.100'
net_connect = netmiko.ConnectHandler(**sw1)
net_connect.enable()
get_time1 = net_connect.send_command_timing('show logging | inc LOGIN-5-LOGIN_SUCCESS')
###Lưu vào file tạm#####
f=open('temp1.txt','w')
f.write(get_time1)
f.close()
###Đọc file tạm trên####
f=open('temp1.txt','r')
lines=f.readlines()
for line in lines:
# các line có dạng [user:admin] login at 14:36:05 ICT Tue Apr 11 2023
time_log = re.findall(r'(?:at) (\d\d:\d\d:\d\d).*(\w\w\w \w\w\w \d\d\ \d\d\d\d)',line)
user_login = re.findall(r'\[user:.*\]',line)
for time1 in time_log:
####Lấy thời gian login trong dòng text trên####
hour=time1[0].split(":")[0]
minute=time1[0].split(":")[1]
second=time1[0].split(":")[2]
day=time1[1].split(" ")[2]
month_abbr=time1[1].split(" ")[1] ##Month in name Apr, May Jul...
mon_number=list(calendar.month_abbr).index(month_abbr)#Quy tháng ra number, ví dụ Apr là 4
year=time1[1].split(" ")[3]
#===============In ra cac lan login cach day 5 phut==================#
hien_tai = datetime.datetime.now()
delta_time=hien_tai-datetime.datetime(int(year),int(mon_number),int(day),int(hour)-4,int(minute),int(second),0)
if int(delta_time.total_seconds())
output="New login found "+ str(user_login)
#================SEND MAIL=====================#
sendMail(output,"haiedubit@outlook.com")
|