【问题标题】:PowerShell and Telnet Integration Outputs Junk CharsPowerShell 和 Telnet 集成输出垃圾字符
【发布时间】:2018-02-14 13:00:07
【问题描述】:

我已尝试让 Telnet 的 PowerShell 自动化连接到 Windows Server 2012 R2、Ubuntu 16.04 和 Windows XP SP3,并且所有服务器都将垃圾字符作为输出。

我正在通过 rfc854,但我无法完成。

你能帮我解决这个问题吗?

以下代码将尝试使用凭据和输出目录列表连接 Telnet 服务器。

代码

param (
    [string] $terminalServer = "192.168.19.131",
    [int] $port = 23,
    [string] $username = "username",
    [string] $password = "password",
    [int] $commandDelay = 1000,
    [string] $output = ""
)

function GetOutput {
    ## Create a buffer to receive the response
    $buffer = new-object System.Byte[] 1024
    $encoding = new-object System.Text.AsciiEncoding
    $outputBuffer = ""
    $foundMore = $false
    ## Read all the data available from the stream, writing it to the
    ## output buffer when done.
    do {
        ## Allow data to buffer for a bit
        start-sleep -m 1000
        ## Read what data is available
        $foundmore = $false
        $stream.ReadTimeout = 2000
        do {
            try {
            $read = $stream.Read($buffer, 0, 1024)
                if($read -gt 0) {
                    $foundmore = $true
                        $outputBuffer += ($encoding.GetString($buffer, 0, $read))
                }
            } catch { $foundMore = $false; $read = 0 }
        } while($read -gt 0)

    } while($foundmore)

    $outputBuffer
}

$output = ""

write-host "Connecting to $terminalServer on port $port..."
trap { Write-Error "Could not connect to the server: $_"; exit }

$socket = new-object System.Net.Sockets.TcpClient($terminalServer, $port)
write-host "Connected. `n"
$stream = $socket.GetStream()
$writer = new-object System.IO.StreamWriter $stream

## Receive the output that has buffered so far
$SCRIPT:output += GetOutput

$writer.WriteLine($username)
$writer.Flush()
Start-Sleep -m $commandDelay

$SCRIPT:output += GetOutput

$writer.WriteLine($password)
$writer.Flush()
Start-Sleep -m $commandDelay

$SCRIPT:output += GetOutput

$writer.WriteLine("dir")
$writer.Flush()
Start-Sleep -m $commandDelay

$SCRIPT:output += GetOutput

$writer.WriteLine("exit")
$writer.Flush()
Start-Sleep -m $commandDelay

## Close the streams
$writer.Close()
$stream.Close()

write-host "All streams are closed. The final output is"
$output

输出

D:\Tools\T24\PowerShell>powershell .\telnet_test.ps1
Connecting to 192.168.19.131 on port 23...
Connected.

All streams are closed. The final output is
??%??????'???? ??

【问题讨论】:

  • “垃圾”很可能是一系列 Telnet 控制字符。考虑使用一些现成的 Telnet 库,而不是原始 TCP。
  • 谢谢@vonPryz。您推荐任何特定的 PowerShell 库吗?我尝试了一些但没有帮助。
  • 不幸的是,没有。 old a question中提到的不少。

标签: powershell scripting telnet


【解决方案1】:

我已经尝试在 Windows Server 2012 R2 上使用 jBASE Telnetd Server 版本 4.1.1 并完美列出目录。

因此,Windows 版本的 Telnet 需要根据 rfc854 实现进行更多操作。

【讨论】:

    猜你喜欢
    • 2016-01-15
    • 1970-01-01
    • 2015-04-29
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    • 2017-11-23
    • 2023-03-20
    相关资源
    最近更新 更多