eiginn
12/6/2015 - 6:47 AM

netstat.py

#!/usr/bin/env python
# GistID: 9017260c676865aa6551

import re
import sys

TCP_EXTRACTOR = re.compile(r"""^\s*
(\d+):\s                                     # sl                        -  0
([\dA-F]{8}(?:[\dA-F]{24})?):([\dA-F]{4})\s  # local address and port    -  1 y  2
([\dA-F]{8}(?:[\dA-F]{24})?):([\dA-F]{4})\s  # remote address and port   -  3 y  4
([\dA-F]{2})\s                               # st                        -  5
([\dA-F]{8}):([\dA-F]{8})\s                  # tx_queue and rx_queue     -  6 y  7
(\d\d):([\dA-F]{8}|(?:F{9,}))\s              # tr and tm->when           -  8 y  9
([\dA-F]{8})\s+                              # retrnsmt                  - 10
(\d+)\s+                                     # uid                       - 11
(\d+)\s+                                     # timeout                   - 12
(\d+)\s+                                     # inode                     - 13
(\d+)\s+                                     # ref count                 - 14
((?:[\dA-F]{8}){1,2})                        # memory address            - 15
(?:
   \s+
   (\d+)\s+                                 # retransmit timeout        - 16
   (\d+)\s+                                 # predicted tick            - 17
   (\d+)\s+                                 # ack.quick                 - 18
   (\d+)\s+                                 # sending congestion window - 19
   (-?\d+)                                  # slow start size threshold - 20
)?
\s*
(.*)                                         # more                      - 21
$""", re.X | re.IGNORECASE)

matches = []
with open("/proc/net/tcp", "r") as f:
    for line in f.readlines():
        matches.append(TCP_EXTRACTOR.match(line))

for i in matches:
    try:
        i = i.groups()
        if int(i[10]) > 0:
            print i
    except:
        pass