【发布时间】:2015-06-27 21:14:23
【问题描述】:
我写了一个小小的 Powershell 脚本。
它使用 .Net System.IO.StreamReader 和 System.IO.StreamWriter 从/向 TCP 套接字读取和写入数据。
我想用它连接到套接字 telnet 样式并发送/接收命令。
我正在尝试使用 System.IO.StreamReader 中的 ReadLine() 方法读取行,但来自服务器的数据可能没有及时到达(?)或 IDK。我没有使用异步命令。请帮帮我!
这是我的脚本:
$FTPServer = "localhost"
$FTPPort = "21"
$tcpConnection = New-Object System.Net.Sockets.TcpClient($FTPServer, $FTPPort)
$tcpStream = $tcpConnection.GetStream()
$reader = New-Object System.IO.StreamReader($tcpStream)
$writer = New-Object System.IO.StreamWriter($tcpStream)
$writer.AutoFlush = $true
while ($tcpConnection.Connected)
{
while ($tcpStream.DataAvailable)
{
$reader.ReadLine()
}
if ($tcpConnection.Connected)
{
Write-Host -NoNewline "prompt> "
$command = Read-Host
if ($command -eq "escape")
{
break
}
$writer.WriteLine($command) | Out-Null
}
}
$reader.Close()
$writer.Close()
$tcpConnection.Close()
这是输出:
PS C:\Windows\System32\WindowsPowerShell\v1.0> test.ps1
220 Microsoft FTP Service
prompt> user username
331 Password required
prompt> pass password
230-Directory has 58,145,996,800 bytes of disk space available.
prompt>
230 User logged in.
500 Command not understood.
prompt> help
214-The following commands are recognized (* ==>'s unimplemented).
ABOR
ACCT
ADAT *
ALLO
APPE
AUTH
CCC
CDUP
CWD
DELE
ENC *
EPRT
EPSV
FEAT
HELP
HOST
LANG
LIST
MDTM
MIC *
MKD
MODE
NLST
NOOP
OPTS
PASS
PASV
PBSZ
PORT
PROT
PWD
QUIT
REIN
REST
RETR
RMD
RNFR
RNTO
SITE
prompt> escape
PS C:\Windows\System32\WindowsPowerShell\v1.0>
【问题讨论】:
标签: .net sockets powershell tcp