Use Python to find 9 contiguous idle ports

Source: Internet
Author: User
Tags domain name server
This article mainly introduces Python to find out 9 consecutive free ports, the interested partners can refer to

First, the project needs

To install a software, configure the time to fill out the idle port. See if a port on one of 5 platforms is occupied

5 platforms for Windows, Linux, AIX, HP, Solaris

Second, there are two ways to achieve the solution

1, using the Python socket module


def isinuse (IPList, Port):  s = socket.socket (socket.af_inet, socket. SOCK_STREAM)  flag=true for  IP in IPList:    try:      s.connect ((IP, int (port)))      S.shutdown (2)      print '%d is inuse '% port      flag=true      break    except:      print '%d was free '% port      flag=false  Return flag


In the Try module if the s.connect ((IP, int (port)) is successful, the port is occupied.

Otherwise, connect is unsuccessful and will go into except, indicating that the port is not occupied.

However, there is a problem, port monitoring IP in addition to "127.0.0.1", "0.0.0.0" may also be native LAN IP such as 222.25.136.17, or the IP of the machine with which to communicate.

The LAN IP can be obtained by this method


Def getlocalip ():  localip = Socket.gethostbyname (Socket.gethostname ())  return Localip


This code only for iplist = ("127.0.0.1", "0.0.0.0", Getlocalip ()) These 3 IP to connect


Import Sysimport osimport socketdef isinuse (IPList, Port):  s = socket.socket (socket.af_inet, socket. SOCK_STREAM)  flag=true for  IP in IPList:    try:      s.connect ((IP, int (port)))      S.shutdown (2)      print '%d is inuse '% port      flag=true      break    except:      print '%d was free '% port      flag=false  return Flagdef Getlocalip ():  localip = Socket.gethostbyname (Socket.gethostname ())  return localipdef Checknineport (startport):  flag = True  IPList = ("127.0.0.1", "0.0.0.0", Getlocalip ()) for  I in range (1, ):    if (Isinuse (IPList, Startport)):      flag = False break    Else:      startport = startport + 1  return flag, Startportdef Findport (startport):  while True:    flag, Endport = Checknineport (startport)    if (flag = = True): #ninePort is ok to break    else:      startport = endport + 1  return startportdef main ( ):  startport=51988  # startport = Int (sys.argv[1])  print Findport (startport) Main ()


2. Find port number matching using netstat output information

The accuracy of the first method depends on the IP in Connect ((IP, int (port))), exactly what kind of IP collection is complete, you can determine that the port is not occupied?

So, here's the way

* * In Linux with NETSTAT-TNPL can get the port monitoring information,

Observe TCP 0 0 10.173.1.208:3210 0.0.0.0:* LISTEN 55563/repserver

10.173.1.208:3210 is present, so 3210 ports are occupied.

Search for this information: 5000, if present, means that port 5000 is listen**.

If the output does not exist: 5000 of the relevant characters, indicating that the port is not occupied.


NETSTAT-TNPL | grep 321tcp 0 0 10.173.1.208:3211 0.0.0.0:* LISTEN 55563/***tcp 0 0 0.0.0.0:3212 0.0.0.0:* LISTEN 55586/***tcp 0 0 10.173.  1.208:3213 0.0.0.0:* LISTEN 55707/***tcp 0 0 0.0.0.0:3214 0.0.0.0:* LISTEN 54272/javatcp 0 0 0.0.0.0:3215 0.0.0.0:* LISTEN  54272/javatcp 0 0 10.173.1.208:3216 0.0.0.0:* LISTEN 54822/***tcp 0 0 10.173.1.208:3217 0.0.0.0:* LISTEN 34959/***tcp 0 0 10.173.1.208:3218 0.0.0.0:* LISTEN 54849/***


According to this idea, give the code.

AIX, HP, WINDOWS, LINUX, SOLARIS These platforms view port information in different ways,

First, the machine platform to judge

Then call the port occupancy judgment function for each platform

If you want to find a contiguous port where one port is occupied, jump out of the loop



Author = ' I316736 ' import osimport platformimport sysdef Isinusewindow (port): If Os.popen (' Netstat-an | findstr: ' + str ( Port). ReadLines (): Portisuse = True print '%d ' is inuse '% port Else:portisuse = False print '%d was free '% Port return portisusedef Isinuselinux (port): #lsof-i:4906 #not show PID to avoid complex if Os.popen (' Netstat-na | g Rep: ' + str (port). ReadLines (): Portisuse = True print '%d is inuse '% port Else:portisuse = False print '% D is free '% port return portisusedef Isinuseaix (port): If Os.popen (' Netstat-aan | grep "\. ' + str (port) + '"). Readli NES (): Portisuse = True print '%d ' inuse '% port Else:portisuse = False print '%d is free '% port return    Portisusedef ISINUSEHP (port): If Os.popen (' netstat-an | grep ' \. ' + str (port) + ' "'). ReadLines (): Portisuse = True print '%d is inuse '% port Else:portisuse = False print '%d was free '% port return portisusedef Isinusesun (port ): If Os.popen (' netstat -an |    grep "\. ' + str (port) + '" '). ReadLines (): Portisuse = True print '%d is inuse '% port Else:portisuse = False print '%d is free '% port return portisusedef chooseplatform (): # ' WINDOWS-7-6.1.7601-SP1 ' # ' Aix-1-00f739ce4c00-powerp C-32bit ' # ' hp-ux-b.11.31-ia64-32bit ' # ' linux-3.0.101-0.35-default-x86_64-with-suse-11-x86_64 ' # ' Sunos-5.10-sun4u-sparc-32bit-elf ' machine = Platform.platform (). Lower () If ' windows-' in Machine:return Isinusewindo    W elif ' linux-' in Machine:return isinuselinux elif ' aix-' in Machine:return isinuseaix elif ' hp-' in machine:    return ISINUSEHP elif ' sunos-' in Machine:return isinusesun else:print ' Error, sorry, platform ' unknown ' Exit ( -1) def checknineport (startport): Isinusefun = Chooseplatform () Nineisfree = True for I in range (1): if (IS Inusefun (Startport)): Nineisfree = False Break Else:startport = startport + 1 return nineisfree, start Portdef Findport (Startport): While True: Flag, Endport = Checknineport (startport) if (flag = = True): # Nineport is ok break else:startport = Endport + 1 return startportdef main (startport): Firstport=findport (startport) print ' first port of nine free ports are    ', firstportif name = = ' main ': If Len (sys.argv) > 1:print len (sys.argv) startport = Int (sys.argv[1]) Else: Startport = Main (Startport)


Summary of relevant knowledge points

Os.popen ()
Some shell commands for the system can be called

Os.popen (). ReadLines ()
Read echo information after invoking a shell command


NETSTAT-TNPL-TNPL the meaning of each parameter-L or--listening displays the socket of the  server in the monitor. -N or--numeric  uses the IP address directly, not through the domain name server. -P or--programs  shows the program identification code and program name that are using the socket. -T or--tcp  shows the connection status of the TCP transport protocol----------TCP 0 0 10.173.1.208:4903 0.0.0.0:* LISTEN 54849/jsagent The last 54849/jsagent represents the process number 54849 Process Name Jsagent
Related Article

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.