Skip to content

Commit c031d7f

Browse files
authored
Update 20.md
Improved topattack script with additional coments in code.
1 parent e44cb9f commit c031d7f

File tree

1 file changed

+35
-13
lines changed

1 file changed

+35
-13
lines changed

docs/20.md

Lines changed: 35 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -69,19 +69,41 @@ Once you're happy with a script, and want to have it easily available, you'll pr
6969

7070
You can expand this script so that it requires a parameter and prints out some syntax help when you don't give one. There are a few new tricks in this, so it's worth studying:
7171

72-
#
73-
## topattack - list the most persistent attackers
74-
#
75-
if [ -z "$1" ]; then
76-
echo -e "\nUsage: `basename $0` <num> - Lists the top <num> attackers by IP"
77-
exit 0
78-
fi
79-
echo " "
80-
echo "Persistant recent attackers"
81-
echo " "
82-
echo "Attempts IP "
83-
echo "-----------------------"
84-
grep "Disconnected from authenticating user root" /var/log/auth.log|cut -d: -f 4 | cut -d" " -f7|sort |uniq -c |sort -nr |head -$1
72+
```
73+
#!/usr/bin/env bash
74+
#
75+
# topattack - list the most persistent attackers
76+
#
77+
# Ensure "graceful exit" in case the script was sourced.
78+
if [[ ${BASH_SOURCE[0]} != "$0" ]]; then
79+
echo "Don't source this file. Execute it.";
80+
return 1;
81+
fi;
82+
# Display usage hint if the script was executed with no/invalid argument.
83+
if [[ -z "$1" ]] || [[ ! "$1" =~ ^[0-9]+$ ]] || (( $1 < 1 )); then
84+
echo -e "\nUsage:\n\t$(basename "${BASH_SOURCE:-$0}") <NUM>";
85+
echo "Lists the top <NUM> attackers by their IP address.";
86+
echo -e "(<NUM> can only be a natural number)\n";
87+
exit 0;
88+
fi;
89+
# Make sure the log file is available for parsing by this user.
90+
if [[ ! -f "/var/log/auth.log" ]] || [[ ! -r "/var/log/auth.log" ]]; then
91+
echo -e "\nI could not read the log file: '/var/log/auth.log'\n";
92+
exit 2;
93+
fi;
94+
# Use 'cat' command and "here document" to avoid repeated 'echo' commands.
95+
cat << _EndOfHeader_
96+
97+
Top $1 persistent recent attackers
98+
99+
Attempts IP
100+
-----------------------
101+
_EndOfHeader_
102+
# Too long command pipelines can be spanned over multiple lines with \
103+
# followed immediately by a newline character (i.e. ENTER, RETURN, '\n')
104+
grep 'Disconnected from authenticating user root' "/var/log/auth.log" \
105+
| cut -d':' -f 4 | cut -d' ' -f 7 | sort | uniq -c | sort -nr | head -n "$1";
106+
```
85107

86108
Again, use vim to create `"topattack"`, `chmod` to make it executable and `mv` to move it into _/usr/local/bin_ once you have it working correctly.
87109

0 commit comments

Comments
 (0)