Shane Smith
Shane Smith

Reputation: 13

How to properly monitor VPS linux command

I ran across this command

watch -n 30 "netstat -ntu | awk '{print \$5}' | cut -d: -f1 | sort | uniq -c | sort -n"

It lists IPs connected to my server, doesn't it? Can someone please break down all the piped commands here and tell me other commands that might be similar for the purpose of server traffic monitoring?

Upvotes: 0

Views: 226

Answers (1)

tripleee
tripleee

Reputation: 189910

watch runs a sequence of commands over and over, with -n 50 every 50 seconds so you can see the output change over time.

netstat displays information about network connections, interfaces, etc. The option -n selects numeric output, -t selects TCP connections, and -u selects UDP. So you are getting a table of active TCP and UDP connections, normalized to just IP addresses and numeric port numbers.

awk and cut are tools to extract just one column. (Or, well, Awk is a simple programming language on its own, so it really could do a lot more.) This should probably be refactored to a single Awk script;

 awk '{ split($5, n, /:/); print n[1] }'

This extracts the stuff before the colon in the fifth column of output, i.e. the IP address without the trailing port number from the netstat output.

(The backslash before the dollar sign in your example is required because the watch command is in double quotes. If you want to run this inside watch, put back the backslash.)

sort | uniq | sort -n is a common idiom for ordering something by number of occurrences. The first sort just puts identical lines next to each other, so that uniq can work correctly (it requires sorted input). With -c, uniq displays how many adjacent lines were merged into one, and then we sort on that number.

So, in summary, you get a list of IP addresses which have connections open to your host, in ascending order. (For this particular use case, descending order would perhaps make more sense -- sort -rn to sort numerically in reverse order.)

If you want to learn these things, it makes sense to split the task into two -- one half is to understand netstat and related networking tools, and the other half is general text processing to extract human-readable information out of potentially large amounts of computer-readable data. For the former, probably look at a network administration handbook. For the latter, maybe look at the GNU coreutils documentation for a start, with a particular focus on the text-processing utilities.

For entertainment value, here is the entire pipeline refactored into mostly Awk.

netstat -ntu |
awk '{ split($5, n, /:/); a[n]++ }
    END { for (ip in a) print a[ip], ip }' |
sort -rn

Upvotes: 0

Related Questions