2014-10-08 112 views
2

我目前正试图将一个查询AD的脚本放到一个计算机列表中,ping计算机以确定哪些计算机仍然处于活动状态,然后telnet到特定端口在所有可ping通的计算机上。我正在查找的输出是AD中完整的可ping计算机列表,我无法telnet到上述端口。如何在Powershell中自动执行Telnet端口检查?

我读过thesefewquestions,但他们并没有打到我想要做的。我只想查看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 
} 
+1

如何从[这里](http://www.powershelladmin.com/wiki/Check_for_open_TCP_ports_using_PowerShell)的简单代码示例。你必须尝试一些连接来测试端口是否打开。 – Matt 2014-10-08 16:24:59

+0

感谢您的建议,马特!我添加了代码(调整后适合我的),但是它将每台计算机都关闭,我知道这并不是真的。我是一个有telnet和powershell的相对新手,但我在这里确信我需要使用telnet来真正做出我需要的决心。 – Justin 2014-10-08 17:34:00

+0

'telnet'命令与@Matt建议的代码完全相同。 – 2014-10-08 18:39:12

回答

3

适应这个代码到你自己将是最简单的方法。此代码示例来自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 
    } 
}