netstat -tn 2>/dev/null | awk '/:80\>/ {print $5}' | cut -d: -f1 | sort | uniq -c | sort -nr | head
This command is useful to detect when your server is under attack, and block those IPs.
netstat -tn
shows the network connections:
-t
: show only connections using the TCP protocol.-n
: show numerical addresses instead of trying to determine symbolic host, port or user names.2> /dev/null
redirects the standard error to /dev/null
, effectively hiding error messages.
awk '/:80\>/ {print $5}'
prints the 5th column for lines that contain the pattern :80
followed by a non-word character. For example ":80 foo"
matches by ":80foo"
does not match. Awk uses whitespaces as column separators by default.
At this point an output line may look like for example 114.198.236.100:80
.
cut -d: -f1
takes the first column of the input, using :
as the field separator.
So effectively it takes the IP address and drops the port number in our example.
sort | uniq -c | sort -nr | head
adds a count for each IP address seen in the input, and shows the top 10, by applying the steps:
sort
simply sorts the input, so that duplicate IP addresses are adjacentuniq -c
groups adjacent lines that are the same and prints them with a count prependedsort -nr
sorts the input numerically and in reverse order. Note that our lines at this point are unique IP addresses, prefixed with the count of connections from them. We use numerical sort with -n
to order by count, and reverse ordering with -r
to make the highest counts come first.head
simply takes the first 10 lines of the inputExample output:
97 114.198.236.100
56 67.166.157.194
44 170.248.43.76
38 141.0.9.20
37 49.248.0.2
37 153.100.131.12
31 223.62.169.73
30 65.248.100.253
29 203.112.82.128
29 182.19.66.187
Source: https://www.mkyong.com/linux/list-all-ip-addresses-connected-to-your-server/