Reputation: 3021
I have automated the deployment of my application via fabric and have a new step that I need to add where I take my application out of rotation in the load balancer then, watch inbound connections from the balancer until they go to 0. Problem is, I am not sure how to get the count of inbound connections.
I can use tcpdump to watch my port POSTs. However, this is kind of hard to use in fabric. What I would like is to just run a loop with a timer that keeps getting the number of active inbound connections and exits on 0. Has anybody done anything like this? Or maybe someone would know how I might be able to achieve this from the shell and I can put it in fabric?
Upvotes: 1
Views: 4151
Reputation: 2811
There might be a slight change somewhere but, this is what's working now.
netstat -an | awk '$1 == "tcp" && $4 ~ /:(80|443)$/' | wc -l
netstat -an | awk '$1 == "tcp" && $5 ~ /:(80|443)$/' | wc -l
From the current netstat help, -n means don't resolve names
but -p only means display PID/Program name for sockets
. So, the check on $4
and $5
in the awk in the above solution would fail.
Additionally, the above command also returns closed ports and other unestablished connections. So, we should use this instead:
netstat -an | awk '$1 == "tcp" && $4 ~ /:(80|443)$/ && $6==ESTABLISHED' | wc -l
netstat -an | awk '$1 == "tcp" && $5 ~ /:(80|443)$/ && $6==ESTABLISHED' | wc -l
Additionally, this also works::
netstat -ap | awk '$1 == "tcp" && $4 ~ /:(http|https)$/' | wc -l
netstat -ap | awk '$1 == "tcp" && $5 ~ /:(http|https)$/' | wc -l
Upvotes: 0
Reputation: 62369
netstat
is one of the simplest ways to get this information, however, as you have noted, simply using grep
to parse the output of netstat
yields sub-optimal results, because it will match both incoming and outgoing connections (at least without a sufficiently complex search expression, or preprocessing with cut
or the like). I would suggest this route, instead:
netstat -ap | awk '$1 == "tcp" && $4 ~ /:(80|443)$/' | wc -l
This will count connections that are TCP-based, and the local end is connected to either port 80 or 443, which would correspond with incoming connections. Replace $4
with $5
in that to catch outgoing connections instead.
Upvotes: 3