Linux 查看远程连接

tao 4月前 84

1.查看登录失败日志

cat /var/log/secure

2. 使用 grep 提取登录失败的信息

grep "Failed password" /var/log/secure

3. 使用 awk 提取关键字段

grep "Failed password" /var/log/secure | awk '{print $1, $2, $3, $9, $11}'

4. 将结果保存到文件

grep "Failed password" /var/log/secure | awk '{print $1, $2, $3, $9, $11}' > failed_attempts.log

5. 定时执行(可选)

crontab -e

添加以下内容,每天凌晨执行一次:

0 0 * * * grep "Failed password" /var/log/secure | awk '{print $1, $2, $3, $9, $11}' > /path/to/failed_attempts.log



方法一:使用 grepawk 命令手动提取

grep "Failed password" /var/log/secure | awk '{print $1, $2, $3, $11, $13}' > /path/to/failed_ssh_logins.txt


方法二:使用 fail2ban 监控 SSH 登录失败

如果希望自动检测并屏蔽这些 IP,可以考虑安装和使用 fail2ban

yum install epel-release -y
yum install fail2ban -y
systemctl enable fail2ban
systemctl start fail2ban

配置文件通常位于 /etc/fail2ban/jail.conf/etc/fail2ban/jail.local,您可以对其进行修改,以便定期阻止多次失败登录的 IP。


方法三:使用脚本自动化日志提取

如果您希望每天定期将这些登录失败的记录导出为文件,您可以编写一个脚本,并将其添加到 crontab 中。

脚本内容 (/usr/local/bin/extract_ssh_fails.sh):

#!/bin/bash
logfile="/var/log/secure"
outputfile="/path/to/failed_ssh_logins_$(date +%F).txt"
grep "Failed password" $logfile | awk '{print $1, $2, $3, $11, $13}' > $outputfile

添加可执行权限:

chmod +x /usr/local/bin/extract_ssh_fails.sh

将脚本添加到 crontab,每天生成一个新文件:

crontab -e

添加以下行:

0 0 * * * /usr/local/bin/extract_ssh_fails.sh

这将在每天午夜自动运行脚本,并将 SSH 登录失败的记录保存在指定的目录中。


  • 确认 /var/log/secure 中的权限,普通用户可能无法访问。
  • 检查防火墙(firewalld)和 SELinux 的限制,确保您有权限读取 /var/log/secure
  • 如果文件太大,您可能只想获取最近的几百行:
tail -n 500 /var/log/secure | grep "Failed password" | awk '{print $1, $2, $3, $11, $13}'



如果要看成功登录的

方法一:使用 grepawk 提取成功登录信息

grep "Accepted" /var/log/secure | awk '{print $1, $2, $3, $9, $11}' > /path/to/successful_ssh_logins.txt


方法二:查看最近的成功登录

如果您只关心最近的成功登录,可以使用 tail 命令来查看 /var/log/secure 中的最后几条记录:

tail -n 100 /var/log/secure | grep "Accepted" | awk '{print $1, $2, $3, $9, $11}'


方法三:使用 last 命令查看所有登录记录

last 命令是一个更简洁的方法,用于显示系统上最近的所有登录用户,包括 SSH 登录。它默认会从 /var/log/wtmp 文件读取数据。

last -a | grep "ssh"



方法四:使用 journalctl 查看登录日志(如果启用了 systemd

如果您的 CentOS 7 配置了 systemd,可以使用 journalctl 来查看系统日志,过滤出 SSH 登录信息。

journalctl -u sshd | grep "Accepted"


  • /var/log/secure 文件可能会因日志轮换而被切割,您可以查看过往的日志文件,如 /var/log/secure-20231010 等。
  • last 命令只显示用户登录的信息,不会显示具体的 SSH 登录方式(密码、密钥等)。如果需要更细粒度的控制,还是建议使用 /var/log/secure


最新回复 (0)
返回
发新帖