#!/usr/bin/python
# zhaoyun
# 统计连接数
import re
import sys
import string
file = '/proc/net/tcp'
'''
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",
'''
class Tcp_count:
def get_contents(self,file):
f = open(file,"r").readlines()
return f
def covert_number(self,number):
value = hex(number)
return value
def get_connect(self,port):
ESTABLISHED = []
SYN_SENT = []
SYN_RECV = []
FIN_WAIT1 = []
FIN_WAIT2 = []
TIME_WAIT = []
CLOSE = []
CLOSE_WAIT = []
CLOSING = []
port = str(self.covert_number(port)).replace("0x","0").upper()
for i in self.get_contents(file):
c = i.split()
p = re.findall(r":.*%(port)s" % vars(),i)
if c[3] == "01" and p:
ESTABLISHED.append(c[3])
if c[3] == "02" and p:
SYN_SENT.append(c[3])
if c[3] == "03" and p:
SYN_RECV.append(c[3])
if c[3] == '04' and p:
FIN_WAIT1.append(c[3])
if c[3] == '05' and p:
FIN_WAIT2.append(c[3])
if c[3] == '06' and p:
TIME_WAIT.append(c[3])
if c[3] == '07' and p:
CLOSE.append(c[3])
if c[3] == '08' and p:
CLOSE_WAIT.append(c[3])
if c[3] == '0B' and p:
CLOSING.append(c[3])
return "ESTABLISHED:\t" + str(len(ESTABLISHED))+" \nSYN_SENT:\t" + str(len(SYN_SENT))+\
"\nSYN_RECV:\t"+str(len(SYN_RECV))+" \nFIN_WAIT1:\t" + str(len(FIN_WAIT1))+\
"\nFIN_WAIT2:\t" + str(len(FIN_WAIT2))+ " \nTIME_WAIT:\t" + str(len(TIME_WAIT))+\
"\nCLOSE: \t" + str(len(CLOSE))+" \nCLOSE_WAIT:\t" + str(len(CLOSE_WAIT))+\
"\nCLOSING:\t"+str(len(CLOSING))
def get_param(para,number):
c = 0
count = 0
p = []
try:
for i in sys.argv:
if i == para:
p.append(sys.argv[c+1])
count+=1
c +=1
if count == int(number):
return string.join(p)
except Exception:
return i+' Parameter Error'
def help_():
print '''
python %s -p 80,443
''' %(sys.argv[0])
p = get_param("-p",1)
if p:
a = Tcp_count()
for i in p.split(","):
try:
print "%s PORT TCP CONNECT STATE"%(i)
print a.get_connect(int(i))
print "\n\n"
except Exception:
pass
else:
help_()
使用方法:
python 1.py -p 80,443
$ python 1.py -p 80,443
80 PORT TCP CONNECT STATE
ESTABLISHED: 77644
SYN_SENT: 0
SYN_RECV: 0
FIN_WAIT1: 9558
FIN_WAIT2: 8260
TIME_WAIT: 354354
CLOSE: 0
CLOSE_WAIT: 0
CLOSING: 0
443 PORT TCP CONNECT STATE
ESTABLISHED: 1180
SYN_SENT: 0
SYN_RECV: 0
FIN_WAIT1: 0
FIN_WAIT2: 118
TIME_WAIT: 2006
CLOSE: 0
CLOSE_WAIT: 0
CLOSING: 0
本文转自zhaoyun00 51CTO博客,原文链接:http://blog.51cto.com/zhaoyun/1236051