Python monitors the number of TCP connections
Python monitors the number of TCP connections
First to understand the next/proc/net/tcp this file, which is recorded in IPv4 all TCP connections, including the following values
SL local_address rem_address St Tx_queue rx_queue tr tm->when retrnsmt uid Timeout inode
Note: The files are all used in the 16 binary we focus on St this column,
Status Code table
Code |
Status Code |
Description |
00 |
Error_status |
|
01 |
Tcp_established |
Represents an open connection |
02 |
Tcp_syn_sent |
Wait for a matching connection request after sending a connection request |
03 |
Tcp_syn_recv |
Wait for confirmation of the connection request after receiving and sending a connection request |
04 |
Tcp_fin_wait1 |
Waiting for a remote TCP connection to interrupt the request, or the acknowledgement of a previous connection interrupt request |
05 |
Tcp_fin_wait2 |
Waiting for connection interrupt request from remote TCP |
06 |
Tcp_time_wait |
Wait enough time to ensure that the remote TCP receives a connection interrupt request acknowledgement |
07 |
Tcp_close |
Wait for the remote TCP acknowledgement of the connection interruption |
08 |
Tcp_close_wait |
Waiting for a connection interrupt request from a local user |
09 |
Tcp_last_ack |
Acknowledgement of the connection interrupt request waiting for the original send to remote TCP |
0A |
Tcp_listen |
Listening for connection requests from a remote TCP port |
0B |
Tcp_closing |
No connection Status |
Python code is as follows
#!/usr/bin/python# coding:utf-8from itertools import dropwhilesys_st = { "xx": "Error_status", ": " tcp_established ", " ": " tcp_syn_sent ", ": "Tcp_syn_recv", ": " tcp_fin_wait1 ", ": "Tcp_fin_wait2", " ": " tcp_time_wait ", " ": " Tcp_close ", ": " Tcp_close_wait ", " ": " 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]&nbsP; 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]] += 1print tcp_static_dict
This article is from the "Linux system Operations Engineer" blog, please be sure to keep this source http://junfeng.blog.51cto.com/1722733/1733804
Python monitors the number of TCP connections