View fail2ban logs instead of lastb to view logon Failure records
Previously, I used a shell script to extract the IP addresses that failed to log on to the server over a specified number of times and add them to iptables to prevent malicious attacks. Fail2ban was installed to provide more comprehensive protection for the host.
This morning, I received an alert email from fail2ban asking me to disable an IP address for Logon. The IP address is 219.235.4.22. After I log on to the host and enter the last command, the result is as follows:
Root ssh: notty host-219-235-4-2 Thu Apr 23)
Root ssh: notty host-219-235-4-2 Thu Apr 23)
Root ssh: notty host-219-235-4-2 Thu Apr 23)
Root ssh: notty host-219-235-4-2 Thu Apr 23)
Root ssh: notty host-219-235-4-2 Thu Apr 23)
Root ssh: notty 61.160.247.150 Thu Apr 23)
Root ssh: notty 61.160.247.150 Thu Apr 23)
Root ssh: notty 61.160.247.150 Thu Apr 23)
There is an additional host, and the IP address is separated by "-". The last IP address cannot be displayed. I immediately thought of viewing the fail2ban log. The default log is/var/log/secure input command:
Grep 'failed password for root from'/var/log/secure | grep '2017. 235.4.22'
The execution result is:
Apr 23 19:32:27 localhost sshd [17856]: Failed password for root from 219.235.4.22 port 4993 ssh2
Apr 23 19:32:30 localhost sshd [17856]: Failed password for root from 219.235.4.22 port 4993 ssh2
Apr 23 19:32:31 localhost sshd [17856]: Failed password for root from 219.235.4.22 port 4993 ssh2
Apr 23 19:32:34 localhost sshd [17856]: Failed password for root from 219.235.4.22 port 4993 ssh2
Apr 23 19:32:36 localhost sshd [17856]: Failed password for root from 219.235.4.22 port 4993 ssh2
At this time, the IP address and the port of the other party are displayed, which is more detailed than lastb. Then I modified the previously written script and directly read/var/log/secure:
#! /Bin/bash
Bad_ip = 'grep' Failed password for root from '/var/log/secure | awk' {print $11, $1, $2} '| sort | uniq-c | awk' $1> 4 {print $2} '| xargs'
For ip in $ bad_ip; do
In_iptables = 'iptables-nvL | grep $ ip | wc-l'
If [$ in_iptables-eq 0]; then
Iptables-I INPUT-s $ ip-j REJECT
Service iptables save
Fi
Done
Run the command. The operation is successful! This article permanently updates the link address: