Netstat continuous refresh (watch changes the output)

79,651

Solution 1

netstat -c

may help you if i've not misunderstood your problem. -c stands for --continuous.

EDIT: there you go:

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

I've added a \ before $.

Solution 2

Monitoring on Ubuntu 18.04 LTS, this worked well. It displays good human-readable output.

sudo netstat -tupnc

Solution 3

Searching for command for macos ends up here. For those mac user who want to see the real-time connections of a process:

nettop -p 60683

You can also restrict the interface type, like wifi or wired...

nettop -t wifi -n -p 60683

Solution 4

Just run a while loop that sleeps for 60 seconds

[root@host] $ while true
> do
> netstat -ntu | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -n
> sleep 60
> done

This will give you the same output every 60 seconds

Share:
79,651
Anton S.
Author by

Anton S.

Updated on September 18, 2022

Comments

  • Anton S.
    Anton S. over 1 year

    I am using this simple command to monitor connections (to deal with some recent DoS attacks) on my Debian server:

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

    How do I run it continuously? So it will refresh itself once per minute (or any given amount of time, of course). I tried watch:

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

    But it changed the output from nice list with num of connections to something like this:

    1 tcp        0  10015 [LOCAL IP]
    ...
    1 Proto Recv-Q Send-Q Local Address           Foreign Address         State
    1 Active Internet connections (w/o servers)
    

    So external IP is not being displayed. Is there something I missed?

    This is how the original output looks:

      2 [IP ADDRESS]
      4 [IP ADDRESS]
      4 [IP ADDRESS]
      4 [IP ADDRESS]
      7 [IP ADDRESS]
     16 [IP ADDRESS]
     71 [IP ADDRESS]
    

    And when I say [LOCAL IP] I mean my machine's IP.

    When I run it with -c it just freezes.

    • Admin
      Admin almost 12 years
      Are you running watch with root privileges? The command looks sound and seems to behave how I would expect on my machine. Running without will not print the addresses and, after 30 seconds might print an error message.
    • Admin
      Admin almost 12 years
      @StewartPlatt I run it under root. I added the original command output. The thing is, when I do watch - it outputs only my IP address ad does not output connected to me IPs at all.
  • MathewCNichols
    MathewCNichols almost 12 years
    already tried, sorry I didn't specify this in a question. It just freezes when I add -c.