Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用VB.net在远程计算机上测试telnet通信?_Vb.net - Fatal编程技术网

使用VB.net在远程计算机上测试telnet通信?

使用VB.net在远程计算机上测试telnet通信?,vb.net,Vb.net,我有一个中央服务器,我需要写一点vb.net,看看我是否可以在指定的端口上远程登录到指定的服务器 在VB.net中是否可以执行此操作?我考虑向远程服务器发送命令提示以执行telnet,然后输出netsh的日志并读取这些日志,然后将信息发送回中央服务器以供查看 这是一种非常混乱的方法,所以我只是想知道是否有更简单的方法您应该使用目标服务器的IP地址和端口创建一个TcpClient对象(对于telnet通常是23)。然后呼叫连接 有关更多信息,请参见此处: 类似这样的情况(可能不准确): 请注意,

我有一个中央服务器,我需要写一点vb.net,看看我是否可以在指定的端口上远程登录到指定的服务器

在VB.net中是否可以执行此操作?我考虑向远程服务器发送命令提示以执行telnet,然后输出netsh的日志并读取这些日志,然后将信息发送回中央服务器以供查看


这是一种非常混乱的方法,所以我只是想知道是否有更简单的方法

您应该使用目标服务器的IP地址和端口创建一个TcpClient对象(对于telnet通常是23)。然后呼叫连接

有关更多信息,请参见此处:

类似这样的情况(可能不准确):


请注意,这是示例代码。完成后,您可能希望清理(关闭/处置)连接(TcpClient)对象等,但这应该可以让您开始。

您应该尝试一些方法来实现这一点。使用.net进行Telnet通信有很多帮助。

从这些指定的链接中获取想法并在vb.net中实现


您可以使用对象而不是 套接字对象,该对象已将套接字参数配置为 使用ProtocolType.Tcp

1.创建一个新的TcpClient对象,该对象采用服务器名称和端口(不需要IPEndPoint,nice)。
2.通过调用GetStream()将网络流从TcpClient中拉出
3.使用Encoding.ASCII.GetBytes(字符串)将消息转换为字节
4.现在您可以分别使用stream.Write和stream.Read方法发送和接收数据。顺便说一下,stream.Read方法返回写入接收数组的字节数。
5.使用Encoding.ASCII.GetString(字节数组)将数据放回人类可读的格式。
6.在网络管理员发疯之前,通过调用stream.Close()和client.Close()清理你的混乱

参考:


我为工作中的一个项目做了这个。 我认为这是一个完全满足大多数人需求的通用解决方案 然而,这是我第一个真正的.net项目,所以请随意评论它

仿效

导入系统线程
导入System.IO
导入System.IO.Pipes
公共类TelnetClient
作为字符串的专用服务器
专用网络协议客户端作为System.Net.Sockets.TcpClient
专用服务器流作为System.Net.Sockets.NetworkStream
私有DoReader作为布尔
私有ReaderThread作为线程
作为匿名PipeServerStream的专用输出管道
私有WaitForString作为字符串
私有WaitForString事件作为新的AutoResetEvent(False)
只读属性IsConnected()为布尔值
得到
返回(非(无任何内容(NetWorkProtocolClient))和(NetWorkProtocolClient.Connected))
结束
端属性
只读属性ConnectedTo()作为字符串
得到
如果(Not(IsNothing(NetWorkProtocolClient))和also(NetWorkProtocolClient.Connected)),则
返回NetWorkProtocolClient.Client.RemoteEndPoint.ToString()
其他的
返回“无”
如果结束
结束
端属性
'设置要连接到的服务器字符串。
公共子设置服务器(ByVal new_server作为字符串)
“稍后再检查一下
服务器=新服务器
端接头
'如果可能,连接。如果已经连接到某个东西,它将从旧的Telnet断开连接并连接到新的Telnet。
公共子连接()
尝试
如果(Not(IsNothing(NetWorkProtocolClient)),并且也是NetWorkProtocolClient.Connected,那么
断开连接()
如果结束
如果不是空(服务器),则
NetWorkProtocolClient=新系统.Net.Sockets.TcpClient(服务器,23)
如果NetWorkProtocolClient.Connected,则
“在新客户上清除
WaitForString=无
WaitForStringEvent.Reset()
NetWorkProtocolClient.NoDelay=True
ServerStream=NetWorkProtocolClient.GetStream()
ServerStream.ReadTimeout=1000
多雷德=真
ReaderThread=新线程(ReaderTask的地址)
ReaderThread.IsBackground=True
ReaderThread.Priority=ThreadPriority.overnormal
ReaderThread.Start()
如果结束
如果结束
Catch ex As System.Net.Sockets.SocketException
WriteLine(“SocketException连接:{0}”,例如)
结束尝试
端接头
'如果已连接,则断开连接,否则不执行任何操作。
公共子系统()
尝试
如果ReaderThread.IsAlive,则
DoReader=False
ReaderThread.Join(1000)
如果结束
如果(不是(IsNothing(NetWorkProtocolClient)),则
ServerStream.Close()
NetWorkProtocolClient.Close()
如果结束
Catch ex As System.Net.Sockets.SocketException
WriteLine(“SocketException Disconnect:{0}”,例如)
结束尝试
端接头
'如果在超时毫秒之前找到,则返回true。使用-1有无限的等待时间。
'如果发生超时,则返回false。
公共函数WaitFor(ByVal命令为字符串,ByVal超时为整数)为布尔值
WaitForString=新字符串(命令)
WaitForStringEvent.Reset()
Dim的信号为布尔=假
'块,直到读卡器或用户定义的超时设置为正确的值
was_signaled=waitForString.WaitOne(超时)
WaitForString=无
返回信号已发出
端函数
公共子写入(ByVal命令作为字符串)
尝试
如果(不是(IsNothing(NetWorkProtocolClient)),则
如果NetWorkProtocolClient.Connected,则
'将值写入流
Dim bytes()的形式为Byte=System.Text.Encoding.ASCII.GetBytes(命令)
同步锁服务器流
ServerStream.Write(字节,0,字节.长度)
端同步
如果结束
如果结束
Catch ex As System.Net.Sockets.SocketException
WriteLine(“SocketException Write:{0}”,例如)
结束尝试
端接头
'为调用方追加CrLf
公共子写入线(ByVal命令作为字符串)
尝试
如果(不是(IsNothing(NetWorkProtocolClient)),则
If NetWorkProtocolClient.Conn
Try

   Dim telnetServerIp As String = "192.168.100.55"
   Dim telnetPort As Integer = 23
   Dim client As New TcpClient(telnetServerIp, telnetPort)
   MessageBox.Show("Server is reachable")
Catch ex As Exception 
   MessageBox.Show("Could not reach server")
End Try
// Create a TcpClient.
    // Note, for this client to work you need to have a TcpServer 
    // connected to the same address as specified by the server, port
    // combination.
    Int32 port = 13000;
    TcpClient client = new TcpClient(server, port);

    // Translate the passed message into ASCII and store it as a Byte array.
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);         

    // Get a client stream for reading and writing.
   //  Stream stream = client.GetStream();

    NetworkStream stream = client.GetStream();

    // Send the message to the connected TcpServer. 
    stream.Write(data, 0, data.Length);

    Console.WriteLine("Sent: {0}", message);  
Imports System.Threading
Imports System.IO
Imports System.IO.Pipes

Public Class TelnetClient
  Private Server As String
  Private NetWorkProtocolClient As System.Net.Sockets.TcpClient
  Private ServerStream As System.Net.Sockets.NetworkStream
  Private DoReader As Boolean
  Private ReaderThread As Thread
  Private OutputPipe As AnonymousPipeServerStream
  Private WaitForString As String
  Private WaitForStringEvent As New AutoResetEvent(False)

  ReadOnly Property IsConnected() As Boolean
    Get
      Return (Not (IsNothing(NetWorkProtocolClient)) AndAlso (NetWorkProtocolClient.Connected))
    End Get
  End Property

  ReadOnly Property ConnectedTo() As String
    Get
      If (Not (IsNothing(NetWorkProtocolClient)) AndAlso (NetWorkProtocolClient.Connected)) Then
        Return NetWorkProtocolClient.Client.RemoteEndPoint.ToString()
      Else
        Return "Nothing"
      End If
    End Get
  End Property

  'Set the Server string to connect to.
  Public Sub SetServer(ByVal new_server As String)
    'double check this later
    Server = new_server
  End Sub
  'Connects if possilbe. If already conneced to some thing it Disconnects from old Telnet and connects to new Telnet.
  Public Sub Connect()
    Try
      If (Not (IsNothing(NetWorkProtocolClient))) AndAlso NetWorkProtocolClient.Connected Then
        Disconnect()
      End If
      If Not IsNothing(Server) Then
        NetWorkProtocolClient = New System.Net.Sockets.TcpClient(Server, 23)
        If NetWorkProtocolClient.Connected Then
          'clear on a new client
          WaitForString = Nothing
          WaitForStringEvent.Reset()

          NetWorkProtocolClient.NoDelay = True
          ServerStream = NetWorkProtocolClient.GetStream()
          ServerStream.ReadTimeout = 1000
          DoReader = True
          ReaderThread = New Thread(AddressOf ReaderTask)
          ReaderThread.IsBackground = True
          ReaderThread.Priority = ThreadPriority.AboveNormal
          ReaderThread.Start()
        End If
      End If
    Catch ex As System.Net.Sockets.SocketException
      Console.WriteLine("SocketException Connect: {0}", ex)
    End Try
  End Sub

  'Disconnects if connected, otherwise does nothing.
  Public Sub Disconnect()
    Try
      If ReaderThread.IsAlive Then
        DoReader = False
        ReaderThread.Join(1000)
      End If
      If (Not (IsNothing(NetWorkProtocolClient))) Then
        ServerStream.Close()
        NetWorkProtocolClient.Close()
      End If
    Catch ex As System.Net.Sockets.SocketException
      Console.WriteLine("SocketException Disconnect: {0}", ex)
    End Try
  End Sub

  'Returns true if found before timeout milliseconds. Use -1 to have infinite wait time.
  'Returns false if timeout occured.
  Public Function WaitFor(ByVal command As String, ByVal timeout As Integer) As Boolean
    WaitForString = New String(command)
    WaitForStringEvent.Reset()
    Dim was_signaled As Boolean = False
    'Block until a the right value from reader or user defined timeout
    was_signaled = WaitForStringEvent.WaitOne(timeout)
    WaitForString = Nothing
    Return was_signaled
  End Function

  Public Sub Write(ByVal command As String)
    Try
      If (Not (IsNothing(NetWorkProtocolClient))) Then
        If NetWorkProtocolClient.Connected Then
          'Write the value to the Stream
          Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(command)
          SyncLock ServerStream
            ServerStream.Write(bytes, 0, bytes.Length)
          End SyncLock
        End If
      End If
    Catch ex As System.Net.Sockets.SocketException
      Console.WriteLine("SocketException Write: {0}", ex)
    End Try
  End Sub

  'appends CrLf for the caller
  Public Sub WriteLine(ByVal command As String)
    Try
      If (Not (IsNothing(NetWorkProtocolClient))) Then
        If NetWorkProtocolClient.Connected Then
          'Write the value to the Stream
          Dim bytes() As Byte = System.Text.Encoding.ASCII.GetBytes(command & vbCrLf)
          SyncLock ServerStream
            ServerStream.Write(bytes, 0, bytes.Length)
          End SyncLock
        End If
      End If
    Catch ex As System.Net.Sockets.SocketException
      Console.WriteLine("SocketException Write: {0}", ex)
    End Try
  End Sub

  'Get a pipe to read output. Note: anything written by WriteLine may be echoed back if the other Telnet offers to do it.
  Public Function GetPipeHandle() As String
    If Not IsNothing(ReaderThread) AndAlso ReaderThread.IsAlive AndAlso Not IsNothing(OutputPipe) Then
      Return OutputPipe.GetClientHandleAsString
    Else
      Return Nothing
    End If
  End Function

  'Task that watches the tcp stream, passes info to the negotiation function and signals the WaitFor task.
  Private Sub ReaderTask()
    Try
      OutputPipe = New AnonymousPipeServerStream(PipeDirection.Out)
      Dim prevData As New String("")
      While (DoReader)
        If (Not (IsNothing(NetWorkProtocolClient))) Then

          If ServerStream.DataAvailable Then

            'Grab Data
            Dim data As [Byte]() = New [Byte](NetWorkProtocolClient.ReceiveBufferSize) {}
            Dim bytes As Integer = ServerStream.Read(data, 0, data.Length)

            'Negotiate anything that came in
            bytes = Negotiate(data, bytes)

            If (bytes > 0) Then
              'append previous to the search sting incase messages were fragmented
              Dim s As New String(prevData & System.Text.ASCIIEncoding.ASCII.GetChars(data))

              'If Pipe is connected send it remaining real data
              If OutputPipe.IsConnected Then
                OutputPipe.Write(data, 0, bytes)
              End If

              'Check remaining against WaitForString
              If Not IsNothing(WaitForString) Then
                If s.Contains(WaitForString) Then
                  WaitForStringEvent.Set()
                  'clear prevData buffer because the WaitForString was found
                  prevData = New String("")
                Else
                  'Nothing found make the current string part of the next string.
                  prevData = New String(s)
                End If
              Else
                prevData = New String("")
              End If
            End If

          Else
            Thread.Sleep(100)
          End If
        End If
      End While
      OutputPipe.Close()
      OutputPipe.Dispose()
    Catch ex As System.IO.IOException
      Console.WriteLine("IO Error: {0}", ex)
    Catch ex As System.Net.Sockets.SocketException
      Console.WriteLine("SocketException Reader: {0}", ex)
    End Try
  End Sub

  'Shamelessly adapted from http://www.codeproject.com/Articles/63201/TelnetSocket
  'The basic algorithm used here is:
  ' Iterate across the incoming bytes
  ' Assume that an IAC (byte 255) is the first of a two- or three-byte Telnet command and handle it:
  '   If two IACs are together, they represent one data byte 255
  '   Ignore the Go-Ahead command
  '   Respond WONT to all DOs and DONTs
  '   Respond DONT to all WONTs
  '   Respond DO to WILL ECHO and WILL SUPPRESS GO-AHEAD
  '   Respond DONT to all other WILLs
  ' Any other bytes are data; ignore nulls, and shift the rest as necessary
  ' Return the number of bytes that remain after removing the Telnet command and ignoring nulls
  Private Function Negotiate(ByVal data As Byte(), ByVal length As Int32) As Int32
    Dim index As Int32 = 0
    Dim remaining As Int32 = 0

    While (index < length)
      If (data(index) = TelnetBytes.IAC) Then
        Try
          Select Case data(index + 1)
            Case TelnetBytes.IAC
              data(remaining) = data(index)
              remaining += 1
              index += 2

            Case TelnetBytes.GA
              index += 2

            Case TelnetBytes.WDO
              data(index + 1) = TelnetBytes.WONT
              SyncLock ServerStream
                ServerStream.Write(data, index, 3)
              End SyncLock
              index += 3

            Case TelnetBytes.DONT
              data(index + 1) = TelnetBytes.WONT
              SyncLock ServerStream
                ServerStream.Write(data, index, 3)
              End SyncLock
              index += 3

            Case TelnetBytes.WONT
              data(index + 1) = TelnetBytes.DONT
              SyncLock ServerStream
                ServerStream.Write(data, index, 3)
              End SyncLock
              index += 3

            Case TelnetBytes.WILL
              Dim action As Byte = TelnetBytes.DONT

              Select Case data(index + 2)

                Case TelnetBytes.ECHO
                  action = TelnetBytes.WDO

                Case TelnetBytes.SUPP
                  action = TelnetBytes.WDO

              End Select
              data(index + 1) = action
              SyncLock ServerStream
                ServerStream.Write(data, index, 3)
              End SyncLock
              index += 3

          End Select

        Catch ex As System.IndexOutOfRangeException
          index = length
        End Try
      Else
        If (data(index) <> 0) Then
          data(remaining) = data(index)
          remaining += 1
        End If
        index += 1
      End If
    End While

    Return remaining
  End Function

  Private Structure TelnetBytes

    'Commands
    Public Const GA As Byte = 249
    Public Const WILL As Byte = 251
    Public Const WONT As Byte = 252
    Public Const WDO As Byte = 253 'Actually just DO but is protected word in vb.net 
    Public Const DONT As Byte = 254
    Public Const IAC As Byte = 255

    'Options
    Public Const ECHO As Byte = 1
    Public Const SUPP As Byte = 3
  End Structure
End Class