p
y
t
h
o
n
查
询
空
闲
端
口
号
python查询空闲端口号
python查询空闲端口号
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):
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 choosePlatform():
machine = platform.platform().lower()
if 'windows-' in machine:
return isInuseWindow
elif 'linux-' in machine:
return isInuseLinux
else:
print('Error, sorry, platform is unknown')
exit(-1)
def checkMutiPort(startPort):
isInuseFun = choosePlatform()
nineIsFree = True
for i in range(1, 2):
if (isInuseFun(startPort)):
nineIsFree = False
break
else:
startPort = startPort + 1
return nineIsFree, startPort
def findPort(startPort):
while True:
flag, endPort = checkMutiPort(startPort)
if (flag == True):
break
else:
startPort = endPort + 1
return startPort
def main(startPort):
firstPort=findPort(startPort)
print('First port of nine free ports is ', firstPort)
if __name__ == '__main__' :
if len(sys.argv) > 1:
print(len(sys.argv))
startPort = int(sys.argv[1])
else:
startPort = 9000
main(startPort)