我写了一个小的Powershell脚本。
它使用 .Net System.IO.StreamReader 和 System.IO.StreamWriter 来从/向TCP套接字读取和写入数据。
我想要用telnet方式连接到套接字并发送/接收命令。
我正在尝试使用System.IO.StreamReader中的ReadLine()方法读取行,但来自服务器的数据可能没有及时到达(?)或者我不知道。我没有使用异步命令。请帮忙解决这个问题!
以下是我的脚本:
$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>