python监控TCP连接数

python监控TCP连接数

先来了解下/proc/net/tcp这个文件,这里记录的是ipv4下所有tcp连接的情况,包括下列数值

sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode

备注:文件中都是用的16进制 我们关注st这列,

状态码对照表

code状态码描述
00ERROR_STATUS
01TCP_ESTABLISHED代表一个打开的连接
02TCP_SYN_SENT在发送连接请求后等待匹配的连接请求
03TCP_SYN_RECV在收到和发送一个连接请求后等待对方对连接请求的确认
04TCP_FIN_WAIT1等待远程TCP连接中断请求,或先前的连接中断请求的确认
05TCP_FIN_WAIT2从远程TCP等待连接中断请求
06TCP_TIME_WAIT等待足够的时间以确保远程TCP接收到连接中断请求的确认
07TCP_CLOSE等待远程TCP对连接中断的确认
08TCP_CLOSE_WAIT等待从本地用户发来的连接中断请求
09TCP_LAST_ACK等待原来的发向远程TCP的连接中断请求的确认
0ATCP_LISTEN侦听来自远方的TCP端口的连接请求
0BTCP_CLOSING没有任何连接状态

python代码如下

#!/usr/bin/python
# coding:utf-8
from itertools import dropwhile

sys_st = {
    "00": "ERROR_STATUS",
    "01": "TCP_ESTABLISHED",
    "02": "TCP_SYN_SENT",
    "03": "TCP_SYN_RECV",
    "04": "TCP_FIN_WAIT1",
    "05": "TCP_FIN_WAIT2",
    "06": "TCP_TIME_WAIT",
    "07": "TCP_CLOSE",
    "08": "TCP_CLOSE_WAIT",
    "09": "TCP_LAST_ACK",
    "0A": "TCP_LISTEN",
    "0B": "TCP_CLOSING",
}

tcp_static_dict = {}

with open("/proc/net/tcp") as f:
    for line in dropwhile(lambda line: line.strip().startswith('sl'), f):
        tcp_status_code = line.split()[3]
        if sys_st.has_key(tcp_status_code):
            if tcp_static_dict.get(sys_st[tcp_status_code], None) is None:
                tcp_static_dict[sys_st[tcp_status_code]] = 1
            else:
                tcp_static_dict[sys_st[tcp_status_code]] += 1
print tcp_static_dict