<
>

Python找出9个连续的空闲端口

2020-06-25 07:30:44 来源:易采站长站 作者:易采站长站整理

出现了 10.173.1.208:3210 所以 3210 端口是被占用的

对这些信息进行搜索 :5000, 如果存在, 就表示5000端口是LISTEN**.

如果输出结果中不存在 :5000 的相关字符,表示这个端口不被占用.


netstat - tnpl | grep 321

tcp 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/java
tcp 0 0 0.0.0.0:3215 0.0.0.0:* LISTEN 54272/java
tcp 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/***

依据这个思路, 给出代码.

AIX 、HP 、WINDOWS、 LINUX、 SOLARIS 这几个平台查看端口信息的方式不同,

先进行机器平台的判断

然后调用各个平台的端口占用判断函数

如果要找出连续端口, 其中只要有一个端口占用, 就跳出循环


__author__ = 'I316736'
import os
import platform
import sys

def isInuseWindow(port):
if os.popen('netstat -an | findstr :' + str(port)).readlines():
portIsUse = True
print '%d is inuse' % port
else:
portIsUse = False
print '%d is free' % port
return portIsUse

def isInuseLinux(port):
#lsof -i:4906
#not show pid to avoid complex
if os.popen('netstat -na | grep :' + str(port)).readlines():
portIsUse = True
print '%d is inuse' % port
else:
portIsUse = False
print '%d is free' % port
return portIsUse

def isInuseAix(port):
if os.popen('netstat -Aan | grep ".' + str(port) + ' "').readlines():
portIsUse = True
print '%d is inuse' % port
else:
portIsUse = False
print '%d is free' % port
return portIsUse

def isInuseHp(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 portIsUse

def 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 portIsUse

def choosePlatform():
#'Windows-7-6.1.7601-SP1'
#'AIX-1-00F739CE4C00-powerpc-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 isInuseWindow
elif 'linux-' in machine:
return isInuseLinux
elif 'aix-' in machine:
return isInuseAix

暂时禁止评论

微信扫一扫

易采站长站微信账号