---
title: "vbs  check port status on local machine"
author: "8366"
date: "2012-01-19T09:49:26Z"
tags: []
categories: ["编程语言"]
slug: "vbs-check-port-status-on-local-machine"
draft: false
lastmod: "2012-01-19T09:49:26Z"
id: 1357900
url: "https://8366.iteye.com/blog/1357900"
---

Dim isOccupied, port  
isOccupied = 0  
    
Do  
    port = InputBox("输入要检查的端口")  
    If IsEmpty(port) Then    'Cancel button is clicked  
        WScript.Quit  
    ElseIf Len(port) = 0 Then  
        MsgBox "No input!", vbExclamation + vbSystemModal  
    ElseIf Not IsNumeric(port) Then  
        MsgBox "Must input a port number!", vbExclamation + vbSystemModal  
    Else  
        Exit Do  
    End If  
Loop  
   
Set WshShell = WScript.CreateObject("WScript.Shell")  
Set oExec = WshShell.Exec("netstat -an")  
Set oStdOut = oExec.StdOut  
Do Until oStdOut.AtEndOfStream  
    strLine = oStdOut.ReadLine  
    WScript.echo strLine  
    If InStr(strLine, ":" & port) &gt; 0 And InStrRev(strLine, "LISTENING") &gt; 0 Then  
        isOccupied = 1  
        Exit Do  
    End If  
Loop

If isOccupied Then  
    MsgBox "端口 " & port & "已经被占用", vbExclamation + vbSystemModal, "Busy"  
Else  
    MsgBox "端口 " & port & " 未被占用", vbInformation + vbSystemModal, "Idle"  
End If

 

 

还有一种 写法， 这种需要计算机上注册mswinsck.ocs 控件，大多数的计算机并没有这个控件，因此下面的这个方法不具有通用性

 

 

'' check the port status from specified server  
'' server : host name or ip address  
'' port : port number  
Function getPortStatus(server,port)  
    Set SockObject=CreateObject("MSWinsock.Winsock.1")  
    SockObject.Protocol=0 ' TCP  
    SockObject.Connect server,port  
    Wscript.Sleep 50  
    If(action = 6) then  
        getPortStatus = "Invalid"  
    ElseIf(SockObject.State = 7) then  
        getPortStatus = "Open"  
    ElseIf(SockObject.State = 9)then  
        getPortStatus = "Error"  
    ElseIf(SockObject.State = 0)then 'Closed  
        getPortStatus = "Refused"  
    Else  
          getPortStatus = "Error"  
    end If  
    SockObject.Close  
End Function