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

Jus*_*tin 2 powershell port tcp telnet

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

我已经阅读了 几个 问题,但他们并没有完全按照我要做的事情来解决.我只是想看看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
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 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
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这是一个完整的 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
Run Code Online (Sandbox Code Playgroud)

清单.csv

remoteHost,port
localhost,80
asdfadsf,83
localhost,135
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

结果.csv

"remoteHost","port","status"
"localhost","80","failed"
"asdfadsf","83","failed"
"localhost","135","success"
Run Code Online (Sandbox Code Playgroud)