python代码tcp连接百度_python监控TCP连接数

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值