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?
watchruns a sequence of commands over and over, with-n 50every 50 seconds so you can see the output change over time.netstatdisplays information about network connections, interfaces, etc. The option-nselects numeric output,-tselects TCP connections, and-uselects UDP. So you are getting a table of active TCP and UDP connections, normalized to just IP addresses and numeric port numbers.awkandcutare 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;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
netstatoutput.(The backslash before the dollar sign in your example is required because the
watchcommand is in double quotes. If you want to run this insidewatch, put back the backslash.)sort | uniq | sort -nis a common idiom for ordering something by number of occurrences. The firstsortjust puts identical lines next to each other, so thatuniqcan work correctly (it requires sorted input). With-c,uniqdisplays 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 -rnto 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
netstatand 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 GNUcoreutilsdocumentation for a start, with a particular focus on the text-processing utilities.For entertainment value, here is the entire pipeline refactored into mostly Awk.