0% found this document useful (0 votes)
8 views5 pages

a

Uploaded by

Jack vanlavong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views5 pages

a

Uploaded by

Jack vanlavong
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

ຄູ່ມືການພັ

ດທະນາລະບົບ Security Log Analysis Tool ບບລະອດ ພາກທີ 1: ການກະກມພື້ນຖານ 1. ການຕິດຕັ້ງ


ລະບົບພື້ນຖານ bashCopy# ອັບເດດລະບົບ sudo apt update sudo apt upgrade -y # ຕິດຕັ້ງ Python ແລະ
pip sudo apt
pasted
J
ແປງເປັນຟາຍ obsidian

ຂ້ອຍຈະຊ່ວຍປງຟາຍນີ້ປັ
ນຮູບບບ Obsidian. ຂ້ອຍຈະແບ່ງເນື້ອຫາເປັນສ່ວນຕ່າງໆ ແລະ ໃຊ້ Markdown syntax:

ຄູ່ມືການພັ
ດທະນາລະບົບ Security Log Analysis Tool
ພາກທີ 1: ການກະກມພື້ນຖານ
1. ການຕິດຕັ້ງລະບົບພື້ນຖານ
bash

Copy
# ອັ
ບເດດລະບົບ
sudo apt update
sudo apt upgrade -y

# ຕິດຕັ້ງ Python ແລະ pip


sudo apt install python3 python3-pip

# ຕິດຕັ້ງ libraries ທີ່ຈຳເປັ



pip3 install pandas numpy matplotlib
pip3 install pymysql sqlalchemy
pip3 install python-dateutil
pip3 install requests
2. ການຕິດຕັ້ງຖານຂໍ້ມູນ
bash

Copy
# ຕິດຕັ້ງ MySQL
sudo apt install mysql-server

# ສ້າງຖານຂໍ້ມູນ
mysql -u root -p
CREATE DATABASE security_logs;
USE security_logs;

# ສ້າງຕາຕະລາງ
CREATE TABLE login_attempts (
id INT AUTO_INCREMENT PRIMARY KEY,
timestamp DATETIME,
ip_address VARCHAR(15),
username VARCHAR(50),
status VARCHAR(20),
attempt_count INT
);

CREATE TABLE attack_logs (


id INT AUTO_INCREMENT PRIMARY KEY,
timestamp DATETIME,
attack_type VARCHAR(50),
source_ip VARCHAR(15),
details TEXT
);
ພາກທີ 2: ການພັ ດທະນາລະບົບ
1. ຄ້ດພື້ນຖານການວິຄາະ Log
python

Copy
import re
import logging
from datetime import datetime
import mysql.connector
from email.mime.text import MIMEText
import smtplib

class SecurityLogAnalyzer:
def __init__(self):
self.db_config = {
'host': 'localhost',
'user': 'root',
'password': 'your_password',
'database': 'security_logs'
}
self.setup_logging()
self.connect_database()

def setup_logging(self):
logging.basicConfig(
filename='security_analyzer.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)

def connect_database(self):
try:
self.conn = mysql.connector.connect(**self.db_config)
self.cursor = self.conn.cursor()
except Exception as e:
logging.error(f"Database connection error: {e}")
raise

def analyze_login_attempts(self, log_file):


failed_attempts = {}

try:
with open(log_file, 'r') as f:
for line in f:
if 'Failed login' in line:
ip = re.search(r'\d+\.\d+\.\d+\.\d+', line).group()
timestamp = re.search(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\
d{2}', line).group()

# ບັ
ນທຶກລົງຖານຂໍ້ມູນ
self.log_attempt(timestamp, ip, 'failed')

# ກວດສອບຈຳນວນຄັ້ງ
if ip in failed_attempts:
failed_attempts[ip] += 1
else:
failed_attempts[ip] = 1

if failed_attempts[ip] >= 5:
self.generate_alert(ip, failed_attempts[ip])
except Exception as e:
logging.error(f"Error analyzing log file: {e}")
2. ລະບົບກວດຈັ
ບການໂຈມຕີ
python

Copy
def detect_attacks(self, log_line):
attack_patterns = {
'sql_injection': r'(UNION|SELECT|INSERT|UPDATE|DELETE|DROP)\s+',
'xss': r'(<script>|javascript:)',
'directory_traversal': r'(\.\.\/|\.\.\\)',
'command_injection': r'(;|\||`).*(sh|bash|cmd)',
'file_inclusion': r'(include|require).*\.(php|ini)'
}

for attack_type, pattern in attack_patterns.items():


if re.search(pattern, log_line, re.I):
self.log_attack(attack_type, log_line)
self.send_alert(f"Detected {attack_type} attack attempt")
3. ລະບົບແຈ້ງເຕືອນ
python

Copy
def send_alert(self, message):
email_config = {
'smtp_server': 'smtp.gmail.com',
'smtp_port': 587,
'username': 'your_email@gmail.com',
'password': 'your_app_password',
'recipients': ['admin@example.com']
}

try:
msg = MIMEText(message)
msg['Subject'] = 'Security Alert'
msg['From'] = email_config['username']
msg['To'] = ', '.join(email_config['recipients'])

with smtplib.SMTP(email_config['smtp_server'], email_config['smtp_port'])


as server:
server.starttls()
server.login(email_config['username'], email_config['password'])
server.send_message(msg)
except Exception as e:
logging.error(f"Error sending alert: {e}")
4. ການສ້າງລາຍງານ
python

Copy
def generate_report(self, start_date, end_date):
report = {
'total_attempts': 0,
'failed_logins': 0,
'attacks_detected': {},
'suspicious_ips': set()
}

try:
query = """
SELECT * FROM login_attempts
WHERE timestamp BETWEEN %s AND %s
"""
self.cursor.execute(query, (start_date, end_date))

for row in self.cursor.fetchall():


report['total_attempts'] += 1
if row['status'] == 'failed':
report['failed_logins'] += 1
if row['attempt_count'] >= 5:
report['suspicious_ips'].add(row['ip_address'])

html_report = self.format_report_html(report)
self.save_report(html_report)
self.send_report_email(html_report)

except Exception as e:
logging.error(f"Error generating report: {e}")
ພາກທີ 3: ການໃຊ້ງານລະບົບ
1. ວິທີການໃຊ້ງານ
python

Copy
if __name__ == "__main__":
analyzer = SecurityLogAnalyzer()

# ວິເຄາະ log file


analyzer.analyze_login_attempts('/var/log/auth.log')

# ສ້າງລາຍງານປະຈຳວັນ
analyzer.generate_report(
start_date=datetime.now().replace(hour=0, minute=0),
end_date=datetime.now()
)
2. ການຕັ້ງຄ່າ Cron Job
bash

Copy
# ເປີດ crontab
crontab -e

# ເພີ່ມການເຮັດວຽກອັດຕະໂນມັດ
0 * * * * /usr/bin/python3 /path/to/security_analyzer.py # ທຸກຊົ່ວໂມງ
0 0 * * * /usr/bin/python3 /path/to/generate_daily_report.py # ທຸກມື້ຕອນເທີ່ງຄືນ
ພາກທີ 4: ການບຳລຸງຮັ ກສາລະບົບ
ການສຳຮອງຂໍ້ມູນປະຈຳວັນ
bash

Copy
mysqldump -u root -p security_logs > backup_$(date +%Y%m%d).sql
ການອະນາໄມ Log ເກົ່າ
python

Copy
def cleanup_old_logs(self, days_to_keep=30):
cleanup_date = datetime.now() - timedelta(days=days_to_keep)
query = "DELETE FROM login_attempts WHERE timestamp < %s"
self.cursor.execute(query, (cleanup_date,))
self.conn.commit()
[[Security]] [[Python]] [[Database]] [[Logging]] [[System Administration]]

You might also like