在 Linux 系统中,SFTP(Secure File Transfer Protocol)日志的查看和分析是确保系统安全性和性能优化的关键步骤。以下是详细的查看和分析方法:
确定日志文件位置:
/var/log/auth.log
或 /var/log/secure
文件中。使用命令查看日志:
cat
命令查看日志文件内容:sudo cat /var/log/auth.log
grep
命令过滤出包含 “sftp” 关键字的日志条目:sudo grep 'sftp' /var/log/auth.log
tail -f
命令实时查看日志文件的活动:sudo tail -f /var/log/auth.log
过滤特定用户的活动:
grep
命令过滤出特定用户的记录:sudo grep 'zhpro' /var/log/auth.log
统计用户连接次数:
awk
命令统计用户连接次数:sudo awk '/zhpro/ {print $1}' /var/log/auth.log | sort | uniq -c
查找失败的登录尝试:
grep
命令过滤出包含 “Failed password” 或 “Login incorrect” 的记录:sudo grep 'Failed password' /var/log/auth.log
查找上传或下载的文件:
grep
命令过滤出包含 “UPLOAD” 或 “DOWNLOAD” 的记录:sudo grep 'UPLOAD' /var/log/auth.log
使用日志分析工具:
sudo logwatch --output mail
sudo fail2ban-client status sshd
以下是一个示例脚本,用于解析用户下载行为并邮件上报:
import os
import datetime
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from datetime import timedelta
def sftp_check():
user_name = 'zhpro'
now = datetime.datetime.now()
yesterday = (now - timedelta(days=1)).strftime('%Y-%m-%d')
file_name = f"/var/log/auth.log_{yesterday}"
ssh_id_list = []
time_action_dict = {}
with open(file_name, "r", encoding='utf-8') as fd:
for line in fd:
if user_name in line:
ssh_id = line.split()[4]
ssh_id_list.append(ssh_id)
with open(file_name, "r", encoding='utf-8') as fd:
for line in fd:
if line.split()[4] in ssh_id_list:
read_key = "flags READ mode 0666"
if read_key in line:
action_time = " ".join(line.split()[0:3])
action_file = line.split()[6]
time_action_dict[action_file] = action_time
return time_action_dict
def smtp_send(file):
mail_host = "smtp.exmail.qq.com"
mail_user = "your_email@example.com"
mail_pass = "your_password"
sender = "your_email@example.com"
receivers = ["receiver1@example.com", "receiver2@example.com"]
with open(file, 'r', encoding='utf-8') as f:
message = MIMEText(f.read(), 'plain', 'utf-8')
message['From'] = Header(sender, 'utf-8')
message['To'] = Header(" ".join(receivers), 'utf-8')
subject = "SFTP Download Activity"
with smtplib.SMTP(mail_host, 25) as server:
server.starttls()
server.login(mail_user, mail_pass)
server.sendmail(sender, receivers, message.as_string())
# 调用函数进行分析并发送邮件
sftp_activity = sftp_check()
smtp_send(str(sftp_activity))
通过上述步骤和工具,你可以有效地查看和分析 Linux SFTP 日志,及时发现并应对潜在的安全威胁。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:怎样分析linux sftp日志