2015-05-05 80 views
0

試圖找出一種方法來自動執行腳本,該腳本將測試端口是否打開或關閉,並返回語句和/或可能發送帶有true或虛假陳述。所以基本上它的一個telnet端口16001,IP 172.x.x.x.我沒有看到登錄到telnet服務器,我只需要知道端口已啓動或關閉。PowerShell腳本來檢查端口是打開還是關閉

回答

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 

看看你是否有一個好的起點。