使用PowerShell进行Telnet

时间:2016-03-08 08:58:31

标签: powershell stream telnet

我使用这个powershell脚本来获取telnet请求的输出流。

Function Get-Telnet {
    Param (
        [Parameter(ValueFromPipeline=$true)]
        [string[]]$Commands = @(),
        [string]$RemoteHost = "0.0.0.0",
        [string]$Port = "23",
        [int]$WaitTime = 1000,
        [string]$OutputPath = "C:\temp\telnet_output.log"
    )
    #Attach to the remote device, setup streaming requirements
    $Socket = New-Object System.Net.Sockets.TcpClient($RemoteHost, $Port)
    if ($Socket) {
        $Stream = $Socket.GetStream()
        $Writer = New-Object System.IO.StreamWriter($Stream)
        $Buffer = New-Object System.Byte[] 1024 
        $Encoding = New-Object System.Text.AsciiEncoding

        #Now start issuing the commands
        foreach ($Command in $Commands) {
            $Writer.WriteLine($Command) 
            $Writer.Flush()
            Start-Sleep -Milliseconds $WaitTime
        }
        #All commands issued, but since the last command is usually going to be
        #the longest let's wait a little longer for it to finish
        Start-Sleep -Milliseconds ($WaitTime * 4)
        $Result = ""
        #Save all the results
        while ($Stream.DataAvailable) {
            $Read = $Stream.Read($Buffer, 0, 1024) 
            $Result += ($Encoding.GetString($Buffer, 0, $Read))
        }
    } else {
        $Result = "Unable to connect to host: $($RemoteHost):$Port"
    }
    #Done, now save the results to a file
    #$Result | Out-File $OutputPath
    $Result
}

这适用于Cisco交换机和telnet服务器,但对于Alcatel OmniPCX和HPUX,流读取为空。

ScreenShot Telnet Output Stream

0 个答案:

没有答案