如何在Powershell中自动执行Telnet端口检查?`

时间:2014-10-08 15:56:22

标签: powershell tcp port telnet

我目前正在尝试整理一个脚本,该脚本查询AD以获取计算机列表,ping计算机以确定哪些计算机仍处于活动状态,然后telnet到所有可ping计算机上的特定端口。我正在寻找的输出是AD中可ping的计算机的完整列表,我无法远程登录到所述端口。

我已阅读these few questions,但他们并没有完全按照我的目标去做。我只是想看看telnet连接是否成功而没有输入telnet(或自动退出telnet)并转到下一台机器进行测试。我的脚本的AD和ping部分已设置,我只是被困在这里。我尝试过的事情并没有按计划进行。

如果需要,以下是脚本第一部分的代码:

Get-ADComputer -Filter * -SearchBase 'DC=hahaha,DC=hehehe' | ForEach {

$computerName = $_.Name

$props = @{
    ComputerName = $computerName
    Alive = $false
    PortOpen = $false
}

If (Test-Connection -ComputerName $computerName -Count 1 -Quiet) {

    $props.Alive = $true
}

2 个答案:

答案 0 :(得分:6)

将此代码改编为您自己的代码是最简单的方法。此代码示例来自PowerShellAdmin wiki。收集您要检查的计算机和端口。然后尝试使用Net.Sockets.TcpClient在每个端口上建立与该计算机的连接。

foreach ($Computer in $ComputerName) {

    foreach ($Port in $Ports) {

        # Create a Net.Sockets.TcpClient object to use for
        # checking for open TCP ports.
        $Socket = New-Object Net.Sockets.TcpClient

        # Suppress error messages
        $ErrorActionPreference = 'SilentlyContinue'

        # Try to connect
        $Socket.Connect($Computer, $Port)

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

        # Determine if we are connected.
        if ($Socket.Connected) {
            "${Computer}: Port $Port is open"
            $Socket.Close()
        }
        else {
            "${Computer}: Port $Port is closed or filtered"  
        }
        # Apparently resetting the variable between iterations is necessary.
        $Socket = $null
    }
}

答案 1 :(得分:2)

以下是一个完整的PowerShell脚本:

1. read the host and port details from CSV file
2. perform telnet test
3. write the output with the test status to another CSV file
  

checklist.csv

remoteHost,port
localhost,80
asdfadsf,83
localhost,135
  

telnet_test.ps1

$checklist = import-csv checklist.csv
$OutArray = @()
Import-Csv checklist.csv |`
ForEach-Object { 
    try {
        $rh = $_.remoteHost
        $p = $_.port
        $socket = new-object System.Net.Sockets.TcpClient($rh, $p)
    } catch [Exception] {
        $myobj = "" | Select "remoteHost", "port", "status"
        $myobj.remoteHost = $rh
        $myobj.port = $p
        $myobj.status = "failed"
        Write-Host $myobj
        $outarray += $myobj
        $myobj = $null
        return
    }
    $myobj = "" | Select "remoteHost", "port", "status"
    $myobj.remoteHost = $rh
    $myobj.port = $p
    $myobj.status = "success"
    Write-Host $myobj
    $outarray += $myobj
    $myobj = $null
    return
}
$outarray | export-csv -path "result.csv" -NoTypeInformation
  

result.csv

"remoteHost","port","status"
"localhost","80","failed"
"asdfadsf","83","failed"
"localhost","135","success"