a
a
ຂ້ອຍຈະຊ່ວຍປງຟາຍນີ້ປັ
ນຮູບບບ Obsidian. ຂ້ອຍຈະແບ່ງເນື້ອຫາເປັນສ່ວນຕ່າງໆ ແລະ ໃຊ້ Markdown syntax:
ຄູ່ມືການພັ
ດທະນາລະບົບ Security Log Analysis Tool
ພາກທີ 1: ການກະກມພື້ນຖານ
1. ການຕິດຕັ້ງລະບົບພື້ນຖານ
bash
Copy
# ອັ
ບເດດລະບົບ
sudo apt update
sudo apt upgrade -y
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
);
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
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)'
}
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'])
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))
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()
# ສ້າງລາຍງານປະຈຳວັນ
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]]