Powershell脚本,用于检查端口是启动还是关闭

时间:2015-05-05 16:07:05

标签: port telnet powershell-v3.0

尝试找出一种自动化脚本的方法,该脚本将测试端口是启动还是关闭并返回语句和/或可能发送带有true或false语句的电子邮件。所以基本上它是一个telnet端口16001,IP 172.x.x.x.我没有看到登录到telnet服务器,我只需要知道端口是向上还是向下。

1 个答案:

答案 0 :(得分:0)

我找到了这段代码,

param([Parameter(Mandatory=$true)][string] $Computer,
  [Parameter(Mandatory=$true)][int[]] $Ports,
  [switch] $Ping,
  [switch] $IgnoreDNS
 )


# I know there are ways to match 0-255 only, but I'm keeping it simple
[bool] $IsIp = $false

if ($Computer -match '\A(?:\d{1,3}\.){3}\d{1,3}\z') {

$IsIp = $true
Write-Output "'$Computer' looks like an IPv4 address. Skipping DNS lookup."

}

if ($IsIp -ne $true) {

Write-Output 'Trying a DNS lookup.'

# Do a DNS lookup with a .NET class method. Suppress error messages.
$ErrorActionPreference = 'SilentlyContinue'

$Ips = [System.Net.Dns]::GetHostAddresses($Computer) | Foreach {$_.IPAddressToString }

if ($?) {

    Write-Output 'IP address(es) from DNS:' ($Ips -join ', ')

}

else {

    if ($IgnoreDNS) {

        Write-Output "WARNING: Could not resolve DNS name, but -IgnoreDNS was specified. Proceeding."

    }

    else {

        Write-Output "Could not resolve DNS name and -IgnoreDNS not specified. Exiting with code 1."
        exit 1

    }

}
# Make errors visible again
$ErrorActionPreference = 'Continue'

}

if ($ping) {

if (Test-Connection -Count 1 -ErrorAction SilentlyContinue $Computer) {

    Write-Output "$Computer responded to ICMP ping"

}

else {

    Write-Output "$Computer did not respond to ICMP ping"

}

}

foreach ($Port in $Ports) {

$private:socket = New-Object Net.Sockets.TcpClient

# Suppress error messages
$ErrorActionPreference = 'SilentlyContinue'

# Try to connect
$private:socket.Connect($Computer, $Port)

# Make error messages visible again
$ErrorActionPreference = 'Continue'

if ($private:socket.Connected) {

    Write-Output "${Computer}: Port $port is open"
    $private:socket.Close()

}

else {

    Write-Output "${Computer}: Port $port is closed or filtered"

}

$private:socket = $null

}

来自http://www.powershelladmin.com/wiki/Check_for_open_TCP_ports_using_PowerShell,但我认为这会给你一个起点,如果你想发送一封电子邮件,你必须包含的代码是

send-mailmessage -to "Email Address" -from "Email address" -subject "PORT is closed" -SmtpServer SMTP Server

看看这是否是一个很好的起点。