Number of TCP connections using the Python statistics port

Source: Internet
Author: User

This script can be used to count the number of connected IPs on a port, and to count all IPs connected to that end, the maximum number of IPs and times, and the status of the TCP connection.

Involves Python reading network connection statistics and some basic operations for statistical calculations. The data structure of statistics is pre-defined during scripting, and the list deduplication function is required when adding statistics to the final result, so a list is temporarily created using the set () function to go heavy. The set () function cannot directly add the dictionary type, so the dictionary is first converted to a hashed string, and then the de-redirected string is converted into a dictionary. Where dictionaries, lists, and collections belong to non-hashed types.

This script can be used for Windows, Linux, and OSX, where OSX runs with root privileges (due to psutil) and is used to run the script file directly using Python. If you are prompted for ' importerror ', use PIP to install the missing modules, and sudo is required for non-privileged users to install modules using PIP.

The script has been set to port 22, you can modify the code to allow it to receive command line position parameters or manual input.

Run as follows:

1. Run with the root user

650) this.width=650; "title=" image "style=" border-top:0px;border-right:0px;border-bottom:0px;border-left:0px; " Border= "0" alt= "image" Src= "Http://s3.51cto.com/wyfs02/M01/89/6C/wKioL1gSxPiD2du0AAF-yYuU_O4020.png" height= "439" />

2. Run with a non-privileged user

650) this.width=650; "title=" image "style=" border-top:0px;border-right:0px;border-bottom:0px;border-left:0px; " Border= "0" alt= "image" Src= "Http://s3.51cto.com/wyfs02/M02/89/6E/wKiom1gSxPnwyTAxAAFMk2TvoMg524.png" height= "407" />

The script file can be obtained from GitHub: https://github.com/DingGuodong/LinuxBashShellScriptForOps/blob/master/functions/net/tcp/port/portStatistics.py

The script reads as follows:

#!/usr/bin/python# encoding: utf-8# -*- coding: utf8 -*-"" "Created by  pycharm.file:                linuxbashshellscriptforops:portstatistics.pyuser:                guodongcreate date:        2016/10/ 27create time:        10:51note:    usage:     using user as you want in linux/windows system.     The python module  ' psutil '  and  ' prettytable '  is  required, using pip    install them.     '      pip install psutil prettytable     '     on  osx this function requires root privileges.    # python portstatistics.py     Total connections of port 22 is 10.     +--------------+-------------------+-------------------+-----------------+--------------+     | Total Counts | Remote IP Address | Established  conns | time_wait conns | others conns |    +---------- ----+-------------------+-------------------+-----------------+--------------+    |       5       |      10.6.28.46    |         5          |        0         |      0       |    |       1       |     10.6.28.35     |         1          |        0         |      0       |     |      1       |      10.6.28.27    |         1          |        0         |      0        |    |      2       |     10.6.28.135    |         2          |        0         |      0        |    |      1        |    10.6.28.125    |          1         |         0        |      0        |    +--------------+-------------------+------------------- +-----------------+--------------+    elapsed time: 0.0104579925537 seconds.    #   "" "Import psutilimport prettytableimport timestarttime = time.time () port =  22  # ssh -i /etc/ssh/ssh_host_rsa_key [email protected]# define  data structure for each connection, each ip is unique  unitipaddress = {     ' ipaddress ': none,     ' counts ':  0,     ' stat ': {         ' established ':  0,         ' time_wait ': 0,          ' others ':  0    }}# define data structure for  statisticsstatistics = {     ' portisused ': false,      ' portusedcounts ':  0,     ' Portpeerlist ': [        {              ' IPAddress ': none,              ' Counts ': 0,              ' stat ': {                  ' established ': 0,                  ' time_wait ': 0,                  ' Others ': 0             },        },    ]} Tmp_portpeerlist = list () Portpeerset = set () netstat = psutil.net_connections () #  get all ip&nbsP;address only for statistics datafor i, sconn in enumerate (netstat):     if port in sconn.laddr:         statistics[' portisused '] = true        if len ( SCONN.RADDR)  != 0:            statistics [' Portusedcounts '] += 1             ipaddress[' IPAddress '] = sconn.raddr[0]             tmp_portpeerlist.append (str (ipaddress))   # dict ()  list ()  set ()  is  unhashable type, collections. Counterfor ip in tmp_portpeerlist:    portpeerset.add (str (IP))   #  remove duplicated ip address using set () for member in portpeerset:    statistics[' portpeerlist '].append (eval (member)) # add  statistics data for each ip addressfor sconn in netstat:     if port in sconn.laddr:        if len ( SCONN.RADDR)  != 0:            for i ,  item in enumerate (statistics[' portpeerlist '):                 if item[' IPAddress '] == sconn.raddr[0]:                      statistics[' portpeerlist '][i][' counts '] += 1                     if sconn.status ==   ' established ':                         statistics[' portpeerlist '][i][' stat ' [' established '] += 1                     elif  sconn.status ==  ' time_wait ':                         statistics[' portPeerList '][i][' Stat ' [' time_wait '] += 1                     else:                         statistics[' Portpeerlist '][i][' stat ' [' Others '] += 1# print statistics result using  prettytableif statistics[' PortiSused ']:    print  "total connections of port %s is %d."  %  (port, statistics[' portusedcounts '])     table = prettytable. Prettytable ()     table.field_names = ["total counts",  "Remote IP  address ", " Established conns ", " Time_wait conns ",                            "Others conns"]    for i, ip in enumerate (statistics[ ' Portpeerlist ']):         if ip[' IPAddress '] is not  none:            table.add_row ([ip[' counts ') ,  ip[' ipaddress '], ip[' stat ' [' established '], ip[' stat '] [' time_wait '],                             ip[' stat ' [' others ']])     print table.get_string (Sortby=table.field_names[1],  reversesort=true) else:    print  ' port %s has no connections ,  please make sure port is listen or in use. '  % portendtime = time.time () print  "Elapsed time: %s seconds."  %  (Endtime - starttime)

Tag: port statistics, Python TCP connections statistics, Python statistics connection number

--end--

This article is from "Communication, My Favorites" blog, please make sure to keep this source http://dgd2010.blog.51cto.com/1539422/1866690

Number of TCP connections using the Python statistics port

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.