需要一个 Powershell 脚本来 ping Linux 服务器的 22 端口

需要一个 Powershell 脚本来 ping Linux 服务器的 22 端口

目前,我正在使用以下命令来获取端口状态。

Test-NetConnection -计算机名称“[服务器名称]”-端口 22 -信息级别 Quiet

使用上述命令,我只能得到 True 或 False。但是,我需要更多。

我想以 5 分钟的间隔和 10 毫秒的超时时间循环它。

有人可以建议怎样做吗?

答案1

修改后的脚本取自PowerShell 代码存储库(作者‘BSonPosh’):

$srv="google.com"
$port=80
$timeout=100 #timeout in miliseconds
$time=300 #Time to check in seconds
$verbose=$true

While($true){

    # Test-Port.ps1
    # Does a TCP connection on specified port (135 by default)

    $ErrorActionPreference = "SilentlyContinue"

    # Create TCP Client
    $tcpclient = new-Object system.Net.Sockets.TcpClient

    # Tell TCP Client to connect to machine on Port
    $iar = $tcpclient.BeginConnect($srv,$port,$null,$null)

    # Set the wait time
    $wait = $iar.AsyncWaitHandle.WaitOne($timeout,$false)

    # Check to see if the connection is done
    if(!$wait)
    {
        # Close the connection and report timeout
        $tcpclient.Close()
        if($verbose){Write-Host "Connection Timeout"}
        Return $false
    }
    else
    {
        # Close the connection and report the error if there is one
        $error.Clear()
        $tcpclient.EndConnect($iar) | out-Null
        if(!$?){if($verbose){write-host $error[0]};$failed = $true}
        $tcpclient.Close()
    }

    # 
    if($failed){Write-Host "Error occured"}else{Write-Host "Ping successfull"}
    Start-Sleep -Seconds $time
   }

相关内容